@ubiquity-os/plugin-sdk 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -42,343 +42,11 @@ module.exports = __toCommonJS(src_exports);
42
42
  // src/actions.ts
43
43
  var core = __toESM(require("@actions/core"));
44
44
  var import_value3 = require("@sinclair/typebox/value");
45
-
46
- // ../../node_modules/@ubiquity-os/ubiquity-os-logger/dist/index.js
47
- var COLORS = {
48
- reset: "\x1B[0m",
49
- bright: "\x1B[1m",
50
- dim: "\x1B[2m",
51
- underscore: "\x1B[4m",
52
- blink: "\x1B[5m",
53
- reverse: "\x1B[7m",
54
- hidden: "\x1B[8m",
55
- fgBlack: "\x1B[30m",
56
- fgRed: "\x1B[31m",
57
- fgGreen: "\x1B[32m",
58
- fgYellow: "\x1B[33m",
59
- fgBlue: "\x1B[34m",
60
- fgMagenta: "\x1B[35m",
61
- fgCyan: "\x1B[36m",
62
- fgWhite: "\x1B[37m",
63
- bgBlack: "\x1B[40m",
64
- bgRed: "\x1B[41m",
65
- bgGreen: "\x1B[42m",
66
- bgYellow: "\x1B[43m",
67
- bgBlue: "\x1B[44m",
68
- bgMagenta: "\x1B[45m",
69
- bgCyan: "\x1B[46m",
70
- bgWhite: "\x1B[47m"
71
- };
72
- var LOG_LEVEL = {
73
- FATAL: "fatal",
74
- ERROR: "error",
75
- WARN: "warn",
76
- INFO: "info",
77
- VERBOSE: "verbose",
78
- DEBUG: "debug"
79
- };
80
- var PrettyLogs = class {
81
- constructor() {
82
- this.ok = this.ok.bind(this);
83
- this.info = this.info.bind(this);
84
- this.error = this.error.bind(this);
85
- this.fatal = this.fatal.bind(this);
86
- this.warn = this.warn.bind(this);
87
- this.debug = this.debug.bind(this);
88
- this.verbose = this.verbose.bind(this);
89
- }
90
- fatal(message, metadata) {
91
- this._logWithStack(LOG_LEVEL.FATAL, message, metadata);
92
- }
93
- error(message, metadata) {
94
- this._logWithStack(LOG_LEVEL.ERROR, message, metadata);
95
- }
96
- warn(message, metadata) {
97
- this._logWithStack(LOG_LEVEL.WARN, message, metadata);
98
- }
99
- ok(message, metadata) {
100
- this._logWithStack("ok", message, metadata);
101
- }
102
- info(message, metadata) {
103
- this._logWithStack(LOG_LEVEL.INFO, message, metadata);
104
- }
105
- debug(message, metadata) {
106
- this._logWithStack(LOG_LEVEL.DEBUG, message, metadata);
107
- }
108
- verbose(message, metadata) {
109
- this._logWithStack(LOG_LEVEL.VERBOSE, message, metadata);
110
- }
111
- _logWithStack(type, message, metaData) {
112
- this._log(type, message);
113
- if (typeof metaData === "string") {
114
- this._log(type, metaData);
115
- return;
116
- }
117
- if (metaData) {
118
- const metadata = metaData;
119
- let stack = metadata?.error?.stack || metadata?.stack;
120
- if (!stack) {
121
- const stackTrace = new Error().stack?.split("\n");
122
- if (stackTrace) {
123
- stackTrace.splice(0, 4);
124
- stack = stackTrace.filter((line) => line.includes(".ts:")).join("\n");
125
- }
126
- }
127
- const newMetadata = { ...metadata };
128
- delete newMetadata.message;
129
- delete newMetadata.name;
130
- delete newMetadata.stack;
131
- if (!this._isEmpty(newMetadata)) {
132
- this._log(type, newMetadata);
133
- }
134
- if (typeof stack == "string") {
135
- const prettyStack = this._formatStackTrace(stack, 1);
136
- const colorizedStack = this._colorizeText(prettyStack, COLORS.dim);
137
- this._log(type, colorizedStack);
138
- } else if (stack) {
139
- const prettyStack = this._formatStackTrace(stack.join("\n"), 1);
140
- const colorizedStack = this._colorizeText(prettyStack, COLORS.dim);
141
- this._log(type, colorizedStack);
142
- } else {
143
- throw new Error("Stack is null");
144
- }
145
- }
146
- }
147
- _colorizeText(text, color) {
148
- if (!color) {
149
- throw new Error(`Invalid color: ${color}`);
150
- }
151
- return color.concat(text).concat(COLORS.reset);
152
- }
153
- _formatStackTrace(stack, linesToRemove = 0, prefix = "") {
154
- const lines = stack.split("\n");
155
- for (let i = 0; i < linesToRemove; i++) {
156
- lines.shift();
157
- }
158
- return lines.map((line) => `${prefix}${line.replace(/\s*at\s*/, " \u21B3 ")}`).join("\n");
159
- }
160
- _isEmpty(obj) {
161
- return !Reflect.ownKeys(obj).some((key) => typeof obj[String(key)] !== "function");
162
- }
163
- _log(type, message) {
164
- const defaultSymbols = {
165
- fatal: "\xD7",
166
- ok: "\u2713",
167
- warn: "\u26A0",
168
- error: "\u26A0",
169
- info: "\u203A",
170
- debug: "\u203A\u203A",
171
- verbose: "\u{1F4AC}"
172
- };
173
- const symbol = defaultSymbols[type];
174
- const messageFormatted = typeof message === "string" ? message : JSON.stringify(message, null, 2);
175
- const lines = messageFormatted.split("\n");
176
- const logString = lines.map((line, index) => {
177
- const prefix = index === 0 ? ` ${symbol}` : ` ${" ".repeat(symbol.length)}`;
178
- return `${prefix} ${line}`;
179
- }).join("\n");
180
- const fullLogString = logString;
181
- const colorMap = {
182
- fatal: ["error", COLORS.fgRed],
183
- ok: ["log", COLORS.fgGreen],
184
- warn: ["warn", COLORS.fgYellow],
185
- error: ["warn", COLORS.fgYellow],
186
- info: ["info", COLORS.dim],
187
- debug: ["debug", COLORS.fgMagenta],
188
- verbose: ["debug", COLORS.dim]
189
- };
190
- const _console = console[colorMap[type][0]];
191
- if (typeof _console === "function" && fullLogString.length > 12) {
192
- _console(this._colorizeText(fullLogString, colorMap[type][1]));
193
- } else if (fullLogString.length <= 12) {
194
- return;
195
- } else {
196
- throw new Error(fullLogString);
197
- }
198
- }
199
- };
200
- var LogReturn = class {
201
- logMessage;
202
- metadata;
203
- constructor(logMessage, metadata) {
204
- this.logMessage = logMessage;
205
- this.metadata = metadata;
206
- }
207
- };
208
- var Logs = class _Logs {
209
- _maxLevel = -1;
210
- static console;
211
- _log({ level, consoleLog, logMessage, metadata, type }) {
212
- if (this._getNumericLevel(level) <= this._maxLevel) {
213
- consoleLog(logMessage, metadata);
214
- }
215
- return new LogReturn(
216
- {
217
- raw: logMessage,
218
- diff: this._diffColorCommentMessage(type, logMessage),
219
- type,
220
- level
221
- },
222
- metadata
223
- );
224
- }
225
- _addDiagnosticInformation(metadata) {
226
- if (!metadata) {
227
- metadata = {};
228
- } else if (typeof metadata !== "object") {
229
- metadata = { message: metadata };
230
- }
231
- const stackLines = new Error().stack?.split("\n") || [];
232
- if (stackLines.length > 3) {
233
- const callerLine = stackLines[3];
234
- const match = callerLine.match(/at (\S+)/);
235
- if (match) {
236
- metadata.caller = match[1];
237
- }
238
- }
239
- return metadata;
240
- }
241
- ok(log, metadata) {
242
- metadata = this._addDiagnosticInformation(metadata);
243
- return this._log({
244
- level: LOG_LEVEL.INFO,
245
- consoleLog: _Logs.console.ok,
246
- logMessage: log,
247
- metadata,
248
- type: "ok"
249
- });
250
- }
251
- info(log, metadata) {
252
- metadata = this._addDiagnosticInformation(metadata);
253
- return this._log({
254
- level: LOG_LEVEL.INFO,
255
- consoleLog: _Logs.console.info,
256
- logMessage: log,
257
- metadata,
258
- type: "info"
259
- });
260
- }
261
- warn(log, metadata) {
262
- metadata = this._addDiagnosticInformation(metadata);
263
- return this._log({
264
- level: LOG_LEVEL.WARN,
265
- consoleLog: _Logs.console.warn,
266
- logMessage: log,
267
- metadata,
268
- type: "warn"
269
- });
270
- }
271
- error(log, metadata) {
272
- metadata = this._addDiagnosticInformation(metadata);
273
- return this._log({
274
- level: LOG_LEVEL.ERROR,
275
- consoleLog: _Logs.console.error,
276
- logMessage: log,
277
- metadata,
278
- type: "error"
279
- });
280
- }
281
- debug(log, metadata) {
282
- metadata = this._addDiagnosticInformation(metadata);
283
- return this._log({
284
- level: LOG_LEVEL.DEBUG,
285
- consoleLog: _Logs.console.debug,
286
- logMessage: log,
287
- metadata,
288
- type: "debug"
289
- });
290
- }
291
- fatal(log, metadata) {
292
- if (!metadata) {
293
- metadata = _Logs.convertErrorsIntoObjects(new Error(log));
294
- const stack = metadata.stack;
295
- stack.splice(1, 1);
296
- metadata.stack = stack;
297
- }
298
- if (metadata instanceof Error) {
299
- metadata = _Logs.convertErrorsIntoObjects(metadata);
300
- const stack = metadata.stack;
301
- stack.splice(1, 1);
302
- metadata.stack = stack;
303
- }
304
- metadata = this._addDiagnosticInformation(metadata);
305
- return this._log({
306
- level: LOG_LEVEL.FATAL,
307
- consoleLog: _Logs.console.fatal,
308
- logMessage: log,
309
- metadata,
310
- type: "fatal"
311
- });
312
- }
313
- verbose(log, metadata) {
314
- metadata = this._addDiagnosticInformation(metadata);
315
- return this._log({
316
- level: LOG_LEVEL.VERBOSE,
317
- consoleLog: _Logs.console.verbose,
318
- logMessage: log,
319
- metadata,
320
- type: "verbose"
321
- });
322
- }
323
- constructor(logLevel) {
324
- this._maxLevel = this._getNumericLevel(logLevel);
325
- _Logs.console = new PrettyLogs();
326
- }
327
- _diffColorCommentMessage(type, message) {
328
- const diffPrefix = {
329
- fatal: "> [!CAUTION]",
330
- error: "> [!CAUTION]",
331
- warn: "> [!WARNING]",
332
- ok: "> [!TIP]",
333
- info: "> [!NOTE]",
334
- debug: "> [!IMPORTANT]",
335
- verbose: "> [!NOTE]"
336
- };
337
- const selected = diffPrefix[type];
338
- if (selected) {
339
- message = message.trim().split("\n").map((line) => `> ${line}`).join("\n");
340
- }
341
- return [selected, message].join("\n");
342
- }
343
- _getNumericLevel(level) {
344
- switch (level) {
345
- case LOG_LEVEL.FATAL:
346
- return 0;
347
- case LOG_LEVEL.ERROR:
348
- return 1;
349
- case LOG_LEVEL.WARN:
350
- return 2;
351
- case LOG_LEVEL.INFO:
352
- return 3;
353
- case LOG_LEVEL.VERBOSE:
354
- return 4;
355
- case LOG_LEVEL.DEBUG:
356
- return 5;
357
- default:
358
- return -1;
359
- }
360
- }
361
- static convertErrorsIntoObjects(obj) {
362
- if (obj instanceof Error) {
363
- return {
364
- message: obj.message,
365
- name: obj.name,
366
- stack: obj.stack ? obj.stack.split("\n") : null
367
- };
368
- } else if (typeof obj === "object" && obj !== null) {
369
- const keys = Object.keys(obj);
370
- keys.forEach((key) => {
371
- obj[key] = this.convertErrorsIntoObjects(obj[key]);
372
- });
373
- }
374
- return obj;
375
- }
376
- };
377
-
378
- // src/actions.ts
45
+ var import_ubiquity_os_logger3 = require("@ubiquity-os/ubiquity-os-logger");
379
46
  var import_dotenv = require("dotenv");
380
47
 
381
48
  // src/error.ts
49
+ var import_ubiquity_os_logger = require("@ubiquity-os/ubiquity-os-logger");
382
50
  function getErrorStatus(err) {
383
51
  if (!err || typeof err !== "object") return null;
384
52
  const candidate = err;
@@ -408,12 +76,12 @@ function logByStatus(context, message, metadata) {
408
76
  return context.logger.error(message, payload);
409
77
  }
410
78
  function transformError(context, error) {
411
- if (error instanceof LogReturn) {
79
+ if (error instanceof import_ubiquity_os_logger.LogReturn) {
412
80
  return error;
413
81
  }
414
82
  if (error instanceof AggregateError) {
415
83
  const message = error.errors.map((err) => {
416
- if (err instanceof LogReturn) {
84
+ if (err instanceof import_ubiquity_os_logger.LogReturn) {
417
85
  return err.logMessage.raw;
418
86
  }
419
87
  if (err instanceof Error) {
@@ -429,55 +97,8 @@ function transformError(context, error) {
429
97
  return logByStatus(context, String(error), { err: error });
430
98
  }
431
99
 
432
- // ../../node_modules/hono/dist/helper/adapter/index.js
433
- var env = (c, runtime) => {
434
- const global = globalThis;
435
- const globalEnv = global?.process?.env;
436
- runtime ??= getRuntimeKey();
437
- const runtimeEnvHandlers = {
438
- bun: () => globalEnv,
439
- node: () => globalEnv,
440
- "edge-light": () => globalEnv,
441
- deno: () => {
442
- return Deno.env.toObject();
443
- },
444
- workerd: () => c.env,
445
- fastly: () => ({}),
446
- other: () => ({})
447
- };
448
- return runtimeEnvHandlers[runtime]();
449
- };
450
- var knownUserAgents = {
451
- deno: "Deno",
452
- bun: "Bun",
453
- workerd: "Cloudflare-Workers",
454
- node: "Node.js"
455
- };
456
- var getRuntimeKey = () => {
457
- const global = globalThis;
458
- const userAgentSupported = typeof navigator !== "undefined" && typeof navigator.userAgent === "string";
459
- if (userAgentSupported) {
460
- for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) {
461
- if (checkUserAgentEquals(userAgent)) {
462
- return runtimeKey;
463
- }
464
- }
465
- }
466
- if (typeof global?.EdgeRuntime === "string") {
467
- return "edge-light";
468
- }
469
- if (global?.fastly !== void 0) {
470
- return "fastly";
471
- }
472
- if (global?.process?.release?.name === "node") {
473
- return "node";
474
- }
475
- return "other";
476
- };
477
- var checkUserAgentEquals = (platform) => {
478
- const userAgent = navigator.userAgent;
479
- return userAgent.startsWith(platform);
480
- };
100
+ // src/helpers/runtime-info.ts
101
+ var import_adapter = require("hono/adapter");
481
102
 
482
103
  // src/helpers/github-context.ts
483
104
  var github = __toESM(require("@actions/github"));
@@ -498,29 +119,29 @@ function getGithubContext() {
498
119
  var PluginRuntimeInfo = class _PluginRuntimeInfo {
499
120
  static _instance = null;
500
121
  _env = {};
501
- constructor(env2) {
502
- if (env2) {
503
- this._env = env2;
122
+ constructor(env) {
123
+ if (env) {
124
+ this._env = env;
504
125
  }
505
126
  }
506
- static getInstance(env2) {
127
+ static getInstance(env) {
507
128
  if (!_PluginRuntimeInfo._instance) {
508
- switch (getRuntimeKey()) {
129
+ switch ((0, import_adapter.getRuntimeKey)()) {
509
130
  case "workerd":
510
- _PluginRuntimeInfo._instance = new CfRuntimeInfo(env2);
131
+ _PluginRuntimeInfo._instance = new CfRuntimeInfo(env);
511
132
  break;
512
133
  case "deno":
513
134
  if (process.env.CI) {
514
- _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env2);
135
+ _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env);
515
136
  } else {
516
- _PluginRuntimeInfo._instance = new DenoRuntimeInfo(env2);
137
+ _PluginRuntimeInfo._instance = new DenoRuntimeInfo(env);
517
138
  }
518
139
  break;
519
140
  case "node":
520
- _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env2);
141
+ _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env);
521
142
  break;
522
143
  default:
523
- _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env2);
144
+ _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env);
524
145
  break;
525
146
  }
526
147
  }
@@ -586,6 +207,9 @@ var DenoRuntimeInfo = class extends PluginRuntimeInfo {
586
207
  }
587
208
  };
588
209
 
210
+ // src/util.ts
211
+ var import_ubiquity_os_logger2 = require("@ubiquity-os/ubiquity-os-logger");
212
+
589
213
  // src/constants.ts
590
214
  var KERNEL_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
591
215
  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs96DOU+JqM8SyNXOB6u3
@@ -624,7 +248,7 @@ function getPluginOptions(options) {
624
248
  return {
625
249
  // Important to use || and not ?? to not consider empty strings
626
250
  kernelPublicKey: options?.kernelPublicKey || KERNEL_PUBLIC_KEY,
627
- logLevel: options?.logLevel || LOG_LEVEL.INFO,
251
+ logLevel: options?.logLevel || import_ubiquity_os_logger2.LOG_LEVEL.INFO,
628
252
  postCommentOnError: options?.postCommentOnError ?? true,
629
253
  settingsSchema: options?.settingsSchema,
630
254
  envSchema: options?.envSchema,
@@ -826,169 +450,7 @@ function decompressString(compressed) {
826
450
 
827
451
  // src/octokit.ts
828
452
  var import_core = require("@octokit/core");
829
-
830
- // ../../node_modules/@octokit/plugin-paginate-graphql/dist-bundle/index.js
831
- var generateMessage = (path, cursorValue) => `The cursor at "${path.join(
832
- ","
833
- )}" did not change its value "${cursorValue}" after a page transition. Please make sure your that your query is set up correctly.`;
834
- var MissingCursorChange = class extends Error {
835
- constructor(pageInfo, cursorValue) {
836
- super(generateMessage(pageInfo.pathInQuery, cursorValue));
837
- this.pageInfo = pageInfo;
838
- this.cursorValue = cursorValue;
839
- if (Error.captureStackTrace) {
840
- Error.captureStackTrace(this, this.constructor);
841
- }
842
- }
843
- name = "MissingCursorChangeError";
844
- };
845
- var MissingPageInfo = class extends Error {
846
- constructor(response) {
847
- super(
848
- `No pageInfo property found in response. Please make sure to specify the pageInfo in your query. Response-Data: ${JSON.stringify(
849
- response,
850
- null,
851
- 2
852
- )}`
853
- );
854
- this.response = response;
855
- if (Error.captureStackTrace) {
856
- Error.captureStackTrace(this, this.constructor);
857
- }
858
- }
859
- name = "MissingPageInfo";
860
- };
861
- var isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
862
- function findPaginatedResourcePath(responseData) {
863
- const paginatedResourcePath = deepFindPathToProperty(
864
- responseData,
865
- "pageInfo"
866
- );
867
- if (paginatedResourcePath.length === 0) {
868
- throw new MissingPageInfo(responseData);
869
- }
870
- return paginatedResourcePath;
871
- }
872
- var deepFindPathToProperty = (object, searchProp, path = []) => {
873
- for (const key of Object.keys(object)) {
874
- const currentPath = [...path, key];
875
- const currentValue = object[key];
876
- if (isObject(currentValue)) {
877
- if (currentValue.hasOwnProperty(searchProp)) {
878
- return currentPath;
879
- }
880
- const result = deepFindPathToProperty(
881
- currentValue,
882
- searchProp,
883
- currentPath
884
- );
885
- if (result.length > 0) {
886
- return result;
887
- }
888
- }
889
- }
890
- return [];
891
- };
892
- var get = (object, path) => {
893
- return path.reduce((current, nextProperty) => current[nextProperty], object);
894
- };
895
- var set = (object, path, mutator) => {
896
- const lastProperty = path[path.length - 1];
897
- const parentPath = [...path].slice(0, -1);
898
- const parent = get(object, parentPath);
899
- if (typeof mutator === "function") {
900
- parent[lastProperty] = mutator(parent[lastProperty]);
901
- } else {
902
- parent[lastProperty] = mutator;
903
- }
904
- };
905
- var extractPageInfos = (responseData) => {
906
- const pageInfoPath = findPaginatedResourcePath(responseData);
907
- return {
908
- pathInQuery: pageInfoPath,
909
- pageInfo: get(responseData, [...pageInfoPath, "pageInfo"])
910
- };
911
- };
912
- var isForwardSearch = (givenPageInfo) => {
913
- return givenPageInfo.hasOwnProperty("hasNextPage");
914
- };
915
- var getCursorFrom = (pageInfo) => isForwardSearch(pageInfo) ? pageInfo.endCursor : pageInfo.startCursor;
916
- var hasAnotherPage = (pageInfo) => isForwardSearch(pageInfo) ? pageInfo.hasNextPage : pageInfo.hasPreviousPage;
917
- var createIterator = (octokit) => {
918
- return (query, initialParameters = {}) => {
919
- let nextPageExists = true;
920
- let parameters = { ...initialParameters };
921
- return {
922
- [Symbol.asyncIterator]: () => ({
923
- async next() {
924
- if (!nextPageExists) return { done: true, value: {} };
925
- const response = await octokit.graphql(
926
- query,
927
- parameters
928
- );
929
- const pageInfoContext = extractPageInfos(response);
930
- const nextCursorValue = getCursorFrom(pageInfoContext.pageInfo);
931
- nextPageExists = hasAnotherPage(pageInfoContext.pageInfo);
932
- if (nextPageExists && nextCursorValue === parameters.cursor) {
933
- throw new MissingCursorChange(pageInfoContext, nextCursorValue);
934
- }
935
- parameters = {
936
- ...parameters,
937
- cursor: nextCursorValue
938
- };
939
- return { done: false, value: response };
940
- }
941
- })
942
- };
943
- };
944
- };
945
- var mergeResponses = (response1, response2) => {
946
- if (Object.keys(response1).length === 0) {
947
- return Object.assign(response1, response2);
948
- }
949
- const path = findPaginatedResourcePath(response1);
950
- const nodesPath = [...path, "nodes"];
951
- const newNodes = get(response2, nodesPath);
952
- if (newNodes) {
953
- set(response1, nodesPath, (values) => {
954
- return [...values, ...newNodes];
955
- });
956
- }
957
- const edgesPath = [...path, "edges"];
958
- const newEdges = get(response2, edgesPath);
959
- if (newEdges) {
960
- set(response1, edgesPath, (values) => {
961
- return [...values, ...newEdges];
962
- });
963
- }
964
- const pageInfoPath = [...path, "pageInfo"];
965
- set(response1, pageInfoPath, get(response2, pageInfoPath));
966
- return response1;
967
- };
968
- var createPaginate = (octokit) => {
969
- const iterator = createIterator(octokit);
970
- return async (query, initialParameters = {}) => {
971
- let mergedResponse = {};
972
- for await (const response of iterator(
973
- query,
974
- initialParameters
975
- )) {
976
- mergedResponse = mergeResponses(mergedResponse, response);
977
- }
978
- return mergedResponse;
979
- };
980
- };
981
- function paginateGraphQL(octokit) {
982
- return {
983
- graphql: Object.assign(octokit.graphql, {
984
- paginate: Object.assign(createPaginate(octokit), {
985
- iterator: createIterator(octokit)
986
- })
987
- })
988
- };
989
- }
990
-
991
- // src/octokit.ts
453
+ var import_plugin_paginate_graphql = require("@octokit/plugin-paginate-graphql");
992
454
  var import_plugin_paginate_rest = require("@octokit/plugin-paginate-rest");
993
455
  var import_plugin_rest_endpoint_methods = require("@octokit/plugin-rest-endpoint-methods");
994
456
  var import_plugin_retry = require("@octokit/plugin-retry");
@@ -1009,7 +471,7 @@ var defaultOptions = {
1009
471
  }
1010
472
  }
1011
473
  };
1012
- var customOctokit = import_core.Octokit.plugin(import_plugin_throttling.throttling, import_plugin_retry.retry, import_plugin_paginate_rest.paginateRest, import_plugin_rest_endpoint_methods.restEndpointMethods, paginateGraphQL).defaults((instanceOptions) => {
474
+ var customOctokit = import_core.Octokit.plugin(import_plugin_throttling.throttling, import_plugin_retry.retry, import_plugin_paginate_rest.paginateRest, import_plugin_rest_endpoint_methods.restEndpointMethods, import_plugin_paginate_graphql.paginateGraphQL).defaults((instanceOptions) => {
1013
475
  return { ...defaultOptions, ...instanceOptions };
1014
476
  });
1015
477
 
@@ -1120,17 +582,17 @@ async function createActionsPlugin(handler, options) {
1120
582
  } else {
1121
583
  config2 = inputs.settings;
1122
584
  }
1123
- let env2;
585
+ let env;
1124
586
  if (pluginOptions.envSchema) {
1125
587
  try {
1126
- env2 = import_value3.Value.Decode(pluginOptions.envSchema, import_value3.Value.Default(pluginOptions.envSchema, process.env));
588
+ env = import_value3.Value.Decode(pluginOptions.envSchema, import_value3.Value.Default(pluginOptions.envSchema, process.env));
1127
589
  } catch (e) {
1128
590
  console.dir(...import_value3.Value.Errors(pluginOptions.envSchema, process.env), { depth: null });
1129
591
  core.setFailed(`Error: Invalid environment provided.`);
1130
592
  throw e;
1131
593
  }
1132
594
  } else {
1133
- env2 = process.env;
595
+ env = process.env;
1134
596
  }
1135
597
  const command = getCommand(inputs, pluginOptions);
1136
598
  const context = {
@@ -1141,8 +603,8 @@ async function createActionsPlugin(handler, options) {
1141
603
  ubiquityKernelToken: inputs.ubiquityKernelToken,
1142
604
  octokit: new customOctokit({ auth: inputs.authToken }),
1143
605
  config: config2,
1144
- env: env2,
1145
- logger: new Logs(pluginOptions.logLevel),
606
+ env,
607
+ logger: new import_ubiquity_os_logger3.Logs(pluginOptions.logLevel),
1146
608
  commentHandler: new CommentHandler()
1147
609
  };
1148
610
  try {
@@ -1197,9 +659,9 @@ function processSegment(segment, extraTags, shouldCollapseEmptyLines) {
1197
659
  return `__INLINE_CODE_${inlineCodes.length - 1}__`;
1198
660
  });
1199
661
  s = s.replace(/<!--[\s\S]*?-->/g, "");
1200
- for (const raw2 of extraTags) {
1201
- if (!raw2) continue;
1202
- const tag = raw2.toLowerCase().trim().replace(/[^\w:-]/g, "");
662
+ for (const raw of extraTags) {
663
+ if (!raw) continue;
664
+ const tag = raw.toLowerCase().trim().replace(/[^\w:-]/g, "");
1203
665
  if (!tag) continue;
1204
666
  if (VOID_TAGS.has(tag)) {
1205
667
  const voidRe = new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi");
@@ -1224,1553 +686,37 @@ function processSegment(segment, extraTags, shouldCollapseEmptyLines) {
1224
686
 
1225
687
  // src/server.ts
1226
688
  var import_value4 = require("@sinclair/typebox/value");
1227
-
1228
- // ../../node_modules/hono/dist/compose.js
1229
- var compose = (middleware, onError, onNotFound) => {
1230
- return (context, next) => {
1231
- let index = -1;
1232
- return dispatch(0);
1233
- async function dispatch(i) {
1234
- if (i <= index) {
1235
- throw new Error("next() called multiple times");
1236
- }
1237
- index = i;
1238
- let res;
1239
- let isError = false;
1240
- let handler;
1241
- if (middleware[i]) {
1242
- handler = middleware[i][0][0];
1243
- context.req.routeIndex = i;
1244
- } else {
1245
- handler = i === middleware.length && next || void 0;
1246
- }
1247
- if (handler) {
1248
- try {
1249
- res = await handler(context, () => dispatch(i + 1));
1250
- } catch (err) {
1251
- if (err instanceof Error && onError) {
1252
- context.error = err;
1253
- res = await onError(err, context);
1254
- isError = true;
1255
- } else {
1256
- throw err;
1257
- }
1258
- }
1259
- } else {
1260
- if (context.finalized === false && onNotFound) {
1261
- res = await onNotFound(context);
1262
- }
1263
- }
1264
- if (res && (context.finalized === false || isError)) {
1265
- context.res = res;
1266
- }
1267
- return context;
1268
- }
1269
- };
1270
- };
1271
-
1272
- // ../../node_modules/hono/dist/request/constants.js
1273
- var GET_MATCH_RESULT = Symbol();
1274
-
1275
- // ../../node_modules/hono/dist/utils/body.js
1276
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
1277
- const { all = false, dot = false } = options;
1278
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
1279
- const contentType = headers.get("Content-Type");
1280
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
1281
- return parseFormData(request, { all, dot });
1282
- }
1283
- return {};
1284
- };
1285
- async function parseFormData(request, options) {
1286
- const formData = await request.formData();
1287
- if (formData) {
1288
- return convertFormDataToBodyData(formData, options);
1289
- }
1290
- return {};
1291
- }
1292
- function convertFormDataToBodyData(formData, options) {
1293
- const form = /* @__PURE__ */ Object.create(null);
1294
- formData.forEach((value, key) => {
1295
- const shouldParseAllValues = options.all || key.endsWith("[]");
1296
- if (!shouldParseAllValues) {
1297
- form[key] = value;
1298
- } else {
1299
- handleParsingAllValues(form, key, value);
1300
- }
1301
- });
1302
- if (options.dot) {
1303
- Object.entries(form).forEach(([key, value]) => {
1304
- const shouldParseDotValues = key.includes(".");
1305
- if (shouldParseDotValues) {
1306
- handleParsingNestedValues(form, key, value);
1307
- delete form[key];
1308
- }
1309
- });
1310
- }
1311
- return form;
1312
- }
1313
- var handleParsingAllValues = (form, key, value) => {
1314
- if (form[key] !== void 0) {
1315
- if (Array.isArray(form[key])) {
1316
- ;
1317
- form[key].push(value);
1318
- } else {
1319
- form[key] = [form[key], value];
1320
- }
1321
- } else {
1322
- if (!key.endsWith("[]")) {
1323
- form[key] = value;
1324
- } else {
1325
- form[key] = [value];
1326
- }
1327
- }
1328
- };
1329
- var handleParsingNestedValues = (form, key, value) => {
1330
- let nestedForm = form;
1331
- const keys = key.split(".");
1332
- keys.forEach((key2, index) => {
1333
- if (index === keys.length - 1) {
1334
- nestedForm[key2] = value;
1335
- } else {
1336
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
1337
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
1338
- }
1339
- nestedForm = nestedForm[key2];
1340
- }
1341
- });
1342
- };
1343
-
1344
- // ../../node_modules/hono/dist/utils/url.js
1345
- var splitPath = (path) => {
1346
- const paths = path.split("/");
1347
- if (paths[0] === "") {
1348
- paths.shift();
1349
- }
1350
- return paths;
1351
- };
1352
- var splitRoutingPath = (routePath) => {
1353
- const { groups, path } = extractGroupsFromPath(routePath);
1354
- const paths = splitPath(path);
1355
- return replaceGroupMarks(paths, groups);
1356
- };
1357
- var extractGroupsFromPath = (path) => {
1358
- const groups = [];
1359
- path = path.replace(/\{[^}]+\}/g, (match, index) => {
1360
- const mark = `@${index}`;
1361
- groups.push([mark, match]);
1362
- return mark;
1363
- });
1364
- return { groups, path };
1365
- };
1366
- var replaceGroupMarks = (paths, groups) => {
1367
- for (let i = groups.length - 1; i >= 0; i--) {
1368
- const [mark] = groups[i];
1369
- for (let j = paths.length - 1; j >= 0; j--) {
1370
- if (paths[j].includes(mark)) {
1371
- paths[j] = paths[j].replace(mark, groups[i][1]);
1372
- break;
1373
- }
1374
- }
1375
- }
1376
- return paths;
1377
- };
1378
- var patternCache = {};
1379
- var getPattern = (label, next) => {
1380
- if (label === "*") {
1381
- return "*";
1382
- }
1383
- const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1384
- if (match) {
1385
- const cacheKey = `${label}#${next}`;
1386
- if (!patternCache[cacheKey]) {
1387
- if (match[2]) {
1388
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
1389
- } else {
1390
- patternCache[cacheKey] = [label, match[1], true];
1391
- }
1392
- }
1393
- return patternCache[cacheKey];
1394
- }
1395
- return null;
1396
- };
1397
- var tryDecode = (str, decoder) => {
1398
- try {
1399
- return decoder(str);
1400
- } catch {
1401
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
1402
- try {
1403
- return decoder(match);
1404
- } catch {
1405
- return match;
1406
- }
1407
- });
1408
- }
1409
- };
1410
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
1411
- var getPath = (request) => {
1412
- const url = request.url;
1413
- const start = url.indexOf(
1414
- "/",
1415
- url.charCodeAt(9) === 58 ? 13 : 8
1416
- );
1417
- let i = start;
1418
- for (; i < url.length; i++) {
1419
- const charCode = url.charCodeAt(i);
1420
- if (charCode === 37) {
1421
- const queryIndex = url.indexOf("?", i);
1422
- const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
1423
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
1424
- } else if (charCode === 63) {
1425
- break;
1426
- }
1427
- }
1428
- return url.slice(start, i);
1429
- };
1430
- var getPathNoStrict = (request) => {
1431
- const result = getPath(request);
1432
- return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
1433
- };
1434
- var mergePath = (base, sub, ...rest) => {
1435
- if (rest.length) {
1436
- sub = mergePath(sub, ...rest);
1437
- }
1438
- return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
1439
- };
1440
- var checkOptionalParameter = (path) => {
1441
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
1442
- return null;
1443
- }
1444
- const segments = path.split("/");
1445
- const results = [];
1446
- let basePath = "";
1447
- segments.forEach((segment) => {
1448
- if (segment !== "" && !/\:/.test(segment)) {
1449
- basePath += "/" + segment;
1450
- } else if (/\:/.test(segment)) {
1451
- if (/\?/.test(segment)) {
1452
- if (results.length === 0 && basePath === "") {
1453
- results.push("/");
1454
- } else {
1455
- results.push(basePath);
1456
- }
1457
- const optionalSegment = segment.replace("?", "");
1458
- basePath += "/" + optionalSegment;
1459
- results.push(basePath);
1460
- } else {
1461
- basePath += "/" + segment;
1462
- }
1463
- }
1464
- });
1465
- return results.filter((v, i, a) => a.indexOf(v) === i);
1466
- };
1467
- var _decodeURI = (value) => {
1468
- if (!/[%+]/.test(value)) {
1469
- return value;
1470
- }
1471
- if (value.indexOf("+") !== -1) {
1472
- value = value.replace(/\+/g, " ");
1473
- }
1474
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
1475
- };
1476
- var _getQueryParam = (url, key, multiple) => {
1477
- let encoded;
1478
- if (!multiple && key && !/[%+]/.test(key)) {
1479
- let keyIndex2 = url.indexOf(`?${key}`, 8);
1480
- if (keyIndex2 === -1) {
1481
- keyIndex2 = url.indexOf(`&${key}`, 8);
1482
- }
1483
- while (keyIndex2 !== -1) {
1484
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
1485
- if (trailingKeyCode === 61) {
1486
- const valueIndex = keyIndex2 + key.length + 2;
1487
- const endIndex = url.indexOf("&", valueIndex);
1488
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
1489
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
1490
- return "";
1491
- }
1492
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1493
- }
1494
- encoded = /[%+]/.test(url);
1495
- if (!encoded) {
1496
- return void 0;
1497
- }
1498
- }
1499
- const results = {};
1500
- encoded ??= /[%+]/.test(url);
1501
- let keyIndex = url.indexOf("?", 8);
1502
- while (keyIndex !== -1) {
1503
- const nextKeyIndex = url.indexOf("&", keyIndex + 1);
1504
- let valueIndex = url.indexOf("=", keyIndex);
1505
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
1506
- valueIndex = -1;
1507
- }
1508
- let name = url.slice(
1509
- keyIndex + 1,
1510
- valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
1511
- );
1512
- if (encoded) {
1513
- name = _decodeURI(name);
1514
- }
1515
- keyIndex = nextKeyIndex;
1516
- if (name === "") {
1517
- continue;
1518
- }
1519
- let value;
1520
- if (valueIndex === -1) {
1521
- value = "";
1522
- } else {
1523
- value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
1524
- if (encoded) {
1525
- value = _decodeURI(value);
1526
- }
1527
- }
1528
- if (multiple) {
1529
- if (!(results[name] && Array.isArray(results[name]))) {
1530
- results[name] = [];
1531
- }
1532
- ;
1533
- results[name].push(value);
1534
- } else {
1535
- results[name] ??= value;
1536
- }
1537
- }
1538
- return key ? results[key] : results;
1539
- };
1540
- var getQueryParam = _getQueryParam;
1541
- var getQueryParams = (url, key) => {
1542
- return _getQueryParam(url, key, true);
1543
- };
1544
- var decodeURIComponent_ = decodeURIComponent;
1545
-
1546
- // ../../node_modules/hono/dist/request.js
1547
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
1548
- var HonoRequest = class {
1549
- raw;
1550
- #validatedData;
1551
- #matchResult;
1552
- routeIndex = 0;
1553
- path;
1554
- bodyCache = {};
1555
- constructor(request, path = "/", matchResult = [[]]) {
1556
- this.raw = request;
1557
- this.path = path;
1558
- this.#matchResult = matchResult;
1559
- this.#validatedData = {};
1560
- }
1561
- param(key) {
1562
- return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1563
- }
1564
- #getDecodedParam(key) {
1565
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1566
- const param = this.#getParamValue(paramKey);
1567
- return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0;
1568
- }
1569
- #getAllDecodedParams() {
1570
- const decoded = {};
1571
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1572
- for (const key of keys) {
1573
- const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1574
- if (value && typeof value === "string") {
1575
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1576
- }
1577
- }
1578
- return decoded;
1579
- }
1580
- #getParamValue(paramKey) {
1581
- return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1582
- }
1583
- query(key) {
1584
- return getQueryParam(this.url, key);
1585
- }
1586
- queries(key) {
1587
- return getQueryParams(this.url, key);
1588
- }
1589
- header(name) {
1590
- if (name) {
1591
- return this.raw.headers.get(name) ?? void 0;
1592
- }
1593
- const headerData = {};
1594
- this.raw.headers.forEach((value, key) => {
1595
- headerData[key] = value;
1596
- });
1597
- return headerData;
1598
- }
1599
- async parseBody(options) {
1600
- return this.bodyCache.parsedBody ??= await parseBody(this, options);
1601
- }
1602
- #cachedBody = (key) => {
1603
- const { bodyCache, raw: raw2 } = this;
1604
- const cachedBody = bodyCache[key];
1605
- if (cachedBody) {
1606
- return cachedBody;
1607
- }
1608
- const anyCachedKey = Object.keys(bodyCache)[0];
1609
- if (anyCachedKey) {
1610
- return bodyCache[anyCachedKey].then((body) => {
1611
- if (anyCachedKey === "json") {
1612
- body = JSON.stringify(body);
1613
- }
1614
- return new Response(body)[key]();
1615
- });
1616
- }
1617
- return bodyCache[key] = raw2[key]();
1618
- };
1619
- json() {
1620
- return this.#cachedBody("text").then((text) => JSON.parse(text));
1621
- }
1622
- text() {
1623
- return this.#cachedBody("text");
1624
- }
1625
- arrayBuffer() {
1626
- return this.#cachedBody("arrayBuffer");
1627
- }
1628
- blob() {
1629
- return this.#cachedBody("blob");
1630
- }
1631
- formData() {
1632
- return this.#cachedBody("formData");
1633
- }
1634
- addValidatedData(target, data) {
1635
- this.#validatedData[target] = data;
1636
- }
1637
- valid(target) {
1638
- return this.#validatedData[target];
1639
- }
1640
- get url() {
1641
- return this.raw.url;
1642
- }
1643
- get method() {
1644
- return this.raw.method;
1645
- }
1646
- get [GET_MATCH_RESULT]() {
1647
- return this.#matchResult;
1648
- }
1649
- get matchedRoutes() {
1650
- return this.#matchResult[0].map(([[, route]]) => route);
1651
- }
1652
- get routePath() {
1653
- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1654
- }
1655
- };
1656
-
1657
- // ../../node_modules/hono/dist/utils/html.js
1658
- var HtmlEscapedCallbackPhase = {
1659
- Stringify: 1,
1660
- BeforeStream: 2,
1661
- Stream: 3
1662
- };
1663
- var raw = (value, callbacks) => {
1664
- const escapedString = new String(value);
1665
- escapedString.isEscaped = true;
1666
- escapedString.callbacks = callbacks;
1667
- return escapedString;
1668
- };
1669
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
1670
- if (typeof str === "object" && !(str instanceof String)) {
1671
- if (!(str instanceof Promise)) {
1672
- str = str.toString();
1673
- }
1674
- if (str instanceof Promise) {
1675
- str = await str;
1676
- }
1677
- }
1678
- const callbacks = str.callbacks;
1679
- if (!callbacks?.length) {
1680
- return Promise.resolve(str);
1681
- }
1682
- if (buffer) {
1683
- buffer[0] += str;
1684
- } else {
1685
- buffer = [str];
1686
- }
1687
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1688
- (res) => Promise.all(
1689
- res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1690
- ).then(() => buffer[0])
1691
- );
1692
- if (preserveCallbacks) {
1693
- return raw(await resStr, callbacks);
1694
- } else {
1695
- return resStr;
1696
- }
1697
- };
1698
-
1699
- // ../../node_modules/hono/dist/context.js
1700
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
1701
- var setDefaultContentType = (contentType, headers) => {
1702
- return {
1703
- "Content-Type": contentType,
1704
- ...headers
1705
- };
1706
- };
1707
- var Context = class {
1708
- #rawRequest;
1709
- #req;
1710
- env = {};
1711
- #var;
1712
- finalized = false;
1713
- error;
1714
- #status;
1715
- #executionCtx;
1716
- #res;
1717
- #layout;
1718
- #renderer;
1719
- #notFoundHandler;
1720
- #preparedHeaders;
1721
- #matchResult;
1722
- #path;
1723
- constructor(req, options) {
1724
- this.#rawRequest = req;
1725
- if (options) {
1726
- this.#executionCtx = options.executionCtx;
1727
- this.env = options.env;
1728
- this.#notFoundHandler = options.notFoundHandler;
1729
- this.#path = options.path;
1730
- this.#matchResult = options.matchResult;
1731
- }
1732
- }
1733
- get req() {
1734
- this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1735
- return this.#req;
1736
- }
1737
- get event() {
1738
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1739
- return this.#executionCtx;
1740
- } else {
1741
- throw Error("This context has no FetchEvent");
1742
- }
1743
- }
1744
- get executionCtx() {
1745
- if (this.#executionCtx) {
1746
- return this.#executionCtx;
1747
- } else {
1748
- throw Error("This context has no ExecutionContext");
1749
- }
1750
- }
1751
- get res() {
1752
- return this.#res ||= new Response(null, {
1753
- headers: this.#preparedHeaders ??= new Headers()
1754
- });
1755
- }
1756
- set res(_res) {
1757
- if (this.#res && _res) {
1758
- _res = new Response(_res.body, _res);
1759
- for (const [k, v] of this.#res.headers.entries()) {
1760
- if (k === "content-type") {
1761
- continue;
1762
- }
1763
- if (k === "set-cookie") {
1764
- const cookies = this.#res.headers.getSetCookie();
1765
- _res.headers.delete("set-cookie");
1766
- for (const cookie of cookies) {
1767
- _res.headers.append("set-cookie", cookie);
1768
- }
1769
- } else {
1770
- _res.headers.set(k, v);
1771
- }
1772
- }
1773
- }
1774
- this.#res = _res;
1775
- this.finalized = true;
1776
- }
1777
- render = (...args) => {
1778
- this.#renderer ??= (content) => this.html(content);
1779
- return this.#renderer(...args);
1780
- };
1781
- setLayout = (layout) => this.#layout = layout;
1782
- getLayout = () => this.#layout;
1783
- setRenderer = (renderer) => {
1784
- this.#renderer = renderer;
1785
- };
1786
- header = (name, value, options) => {
1787
- if (this.finalized) {
1788
- this.#res = new Response(this.#res.body, this.#res);
1789
- }
1790
- const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1791
- if (value === void 0) {
1792
- headers.delete(name);
1793
- } else if (options?.append) {
1794
- headers.append(name, value);
1795
- } else {
1796
- headers.set(name, value);
1797
- }
1798
- };
1799
- status = (status) => {
1800
- this.#status = status;
1801
- };
1802
- set = (key, value) => {
1803
- this.#var ??= /* @__PURE__ */ new Map();
1804
- this.#var.set(key, value);
1805
- };
1806
- get = (key) => {
1807
- return this.#var ? this.#var.get(key) : void 0;
1808
- };
1809
- get var() {
1810
- if (!this.#var) {
1811
- return {};
1812
- }
1813
- return Object.fromEntries(this.#var);
1814
- }
1815
- #newResponse(data, arg, headers) {
1816
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1817
- if (typeof arg === "object" && "headers" in arg) {
1818
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1819
- for (const [key, value] of argHeaders) {
1820
- if (key.toLowerCase() === "set-cookie") {
1821
- responseHeaders.append(key, value);
1822
- } else {
1823
- responseHeaders.set(key, value);
1824
- }
1825
- }
1826
- }
1827
- if (headers) {
1828
- for (const [k, v] of Object.entries(headers)) {
1829
- if (typeof v === "string") {
1830
- responseHeaders.set(k, v);
1831
- } else {
1832
- responseHeaders.delete(k);
1833
- for (const v2 of v) {
1834
- responseHeaders.append(k, v2);
1835
- }
1836
- }
1837
- }
1838
- }
1839
- const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1840
- return new Response(data, { status, headers: responseHeaders });
1841
- }
1842
- newResponse = (...args) => this.#newResponse(...args);
1843
- body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1844
- text = (text, arg, headers) => {
1845
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1846
- text,
1847
- arg,
1848
- setDefaultContentType(TEXT_PLAIN, headers)
1849
- );
1850
- };
1851
- json = (object, arg, headers) => {
1852
- return this.#newResponse(
1853
- JSON.stringify(object),
1854
- arg,
1855
- setDefaultContentType("application/json", headers)
1856
- );
1857
- };
1858
- html = (html, arg, headers) => {
1859
- const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1860
- return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1861
- };
1862
- redirect = (location, status) => {
1863
- const locationString = String(location);
1864
- this.header(
1865
- "Location",
1866
- !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1867
- );
1868
- return this.newResponse(null, status ?? 302);
1869
- };
1870
- notFound = () => {
1871
- this.#notFoundHandler ??= () => new Response();
1872
- return this.#notFoundHandler(this);
1873
- };
1874
- };
1875
-
1876
- // ../../node_modules/hono/dist/router.js
1877
- var METHOD_NAME_ALL = "ALL";
1878
- var METHOD_NAME_ALL_LOWERCASE = "all";
1879
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1880
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1881
- var UnsupportedPathError = class extends Error {
1882
- };
1883
-
1884
- // ../../node_modules/hono/dist/utils/constants.js
1885
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1886
-
1887
- // ../../node_modules/hono/dist/hono-base.js
1888
- var notFoundHandler = (c) => {
1889
- return c.text("404 Not Found", 404);
1890
- };
1891
- var errorHandler = (err, c) => {
1892
- if ("getResponse" in err) {
1893
- const res = err.getResponse();
1894
- return c.newResponse(res.body, res);
1895
- }
1896
- console.error(err);
1897
- return c.text("Internal Server Error", 500);
1898
- };
1899
- var Hono = class {
1900
- get;
1901
- post;
1902
- put;
1903
- delete;
1904
- options;
1905
- patch;
1906
- all;
1907
- on;
1908
- use;
1909
- router;
1910
- getPath;
1911
- _basePath = "/";
1912
- #path = "/";
1913
- routes = [];
1914
- constructor(options = {}) {
1915
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1916
- allMethods.forEach((method) => {
1917
- this[method] = (args1, ...args) => {
1918
- if (typeof args1 === "string") {
1919
- this.#path = args1;
1920
- } else {
1921
- this.#addRoute(method, this.#path, args1);
1922
- }
1923
- args.forEach((handler) => {
1924
- this.#addRoute(method, this.#path, handler);
1925
- });
1926
- return this;
1927
- };
1928
- });
1929
- this.on = (method, path, ...handlers) => {
1930
- for (const p of [path].flat()) {
1931
- this.#path = p;
1932
- for (const m of [method].flat()) {
1933
- handlers.map((handler) => {
1934
- this.#addRoute(m.toUpperCase(), this.#path, handler);
1935
- });
1936
- }
1937
- }
1938
- return this;
1939
- };
1940
- this.use = (arg1, ...handlers) => {
1941
- if (typeof arg1 === "string") {
1942
- this.#path = arg1;
1943
- } else {
1944
- this.#path = "*";
1945
- handlers.unshift(arg1);
1946
- }
1947
- handlers.forEach((handler) => {
1948
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1949
- });
1950
- return this;
1951
- };
1952
- const { strict, ...optionsWithoutStrict } = options;
1953
- Object.assign(this, optionsWithoutStrict);
1954
- this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1955
- }
1956
- #clone() {
1957
- const clone = new Hono({
1958
- router: this.router,
1959
- getPath: this.getPath
1960
- });
1961
- clone.errorHandler = this.errorHandler;
1962
- clone.#notFoundHandler = this.#notFoundHandler;
1963
- clone.routes = this.routes;
1964
- return clone;
1965
- }
1966
- #notFoundHandler = notFoundHandler;
1967
- errorHandler = errorHandler;
1968
- route(path, app) {
1969
- const subApp = this.basePath(path);
1970
- app.routes.map((r) => {
1971
- let handler;
1972
- if (app.errorHandler === errorHandler) {
1973
- handler = r.handler;
1974
- } else {
1975
- handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1976
- handler[COMPOSED_HANDLER] = r.handler;
1977
- }
1978
- subApp.#addRoute(r.method, r.path, handler);
1979
- });
1980
- return this;
1981
- }
1982
- basePath(path) {
1983
- const subApp = this.#clone();
1984
- subApp._basePath = mergePath(this._basePath, path);
1985
- return subApp;
1986
- }
1987
- onError = (handler) => {
1988
- this.errorHandler = handler;
1989
- return this;
1990
- };
1991
- notFound = (handler) => {
1992
- this.#notFoundHandler = handler;
1993
- return this;
1994
- };
1995
- mount(path, applicationHandler, options) {
1996
- let replaceRequest;
1997
- let optionHandler;
1998
- if (options) {
1999
- if (typeof options === "function") {
2000
- optionHandler = options;
2001
- } else {
2002
- optionHandler = options.optionHandler;
2003
- if (options.replaceRequest === false) {
2004
- replaceRequest = (request) => request;
2005
- } else {
2006
- replaceRequest = options.replaceRequest;
2007
- }
2008
- }
2009
- }
2010
- const getOptions = optionHandler ? (c) => {
2011
- const options2 = optionHandler(c);
2012
- return Array.isArray(options2) ? options2 : [options2];
2013
- } : (c) => {
2014
- let executionContext = void 0;
2015
- try {
2016
- executionContext = c.executionCtx;
2017
- } catch {
2018
- }
2019
- return [c.env, executionContext];
2020
- };
2021
- replaceRequest ||= (() => {
2022
- const mergedPath = mergePath(this._basePath, path);
2023
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2024
- return (request) => {
2025
- const url = new URL(request.url);
2026
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2027
- return new Request(url, request);
2028
- };
2029
- })();
2030
- const handler = async (c, next) => {
2031
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2032
- if (res) {
2033
- return res;
2034
- }
2035
- await next();
2036
- };
2037
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2038
- return this;
2039
- }
2040
- #addRoute(method, path, handler) {
2041
- method = method.toUpperCase();
2042
- path = mergePath(this._basePath, path);
2043
- const r = { basePath: this._basePath, path, method, handler };
2044
- this.router.add(method, path, [handler, r]);
2045
- this.routes.push(r);
2046
- }
2047
- #handleError(err, c) {
2048
- if (err instanceof Error) {
2049
- return this.errorHandler(err, c);
2050
- }
2051
- throw err;
2052
- }
2053
- #dispatch(request, executionCtx, env2, method) {
2054
- if (method === "HEAD") {
2055
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env2, "GET")))();
2056
- }
2057
- const path = this.getPath(request, { env: env2 });
2058
- const matchResult = this.router.match(method, path);
2059
- const c = new Context(request, {
2060
- path,
2061
- matchResult,
2062
- env: env2,
2063
- executionCtx,
2064
- notFoundHandler: this.#notFoundHandler
2065
- });
2066
- if (matchResult[0].length === 1) {
2067
- let res;
2068
- try {
2069
- res = matchResult[0][0][0][0](c, async () => {
2070
- c.res = await this.#notFoundHandler(c);
2071
- });
2072
- } catch (err) {
2073
- return this.#handleError(err, c);
2074
- }
2075
- return res instanceof Promise ? res.then(
2076
- (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2077
- ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2078
- }
2079
- const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2080
- return (async () => {
2081
- try {
2082
- const context = await composed(c);
2083
- if (!context.finalized) {
2084
- throw new Error(
2085
- "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2086
- );
2087
- }
2088
- return context.res;
2089
- } catch (err) {
2090
- return this.#handleError(err, c);
2091
- }
2092
- })();
2093
- }
2094
- fetch = (request, ...rest) => {
2095
- return this.#dispatch(request, rest[1], rest[0], request.method);
2096
- };
2097
- request = (input, requestInit, Env, executionCtx) => {
2098
- if (input instanceof Request) {
2099
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2100
- }
2101
- input = input.toString();
2102
- return this.fetch(
2103
- new Request(
2104
- /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2105
- requestInit
2106
- ),
2107
- Env,
2108
- executionCtx
2109
- );
2110
- };
2111
- fire = () => {
2112
- addEventListener("fetch", (event) => {
2113
- event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2114
- });
2115
- };
2116
- };
2117
-
2118
- // ../../node_modules/hono/dist/router/reg-exp-router/node.js
2119
- var LABEL_REG_EXP_STR = "[^/]+";
2120
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
2121
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2122
- var PATH_ERROR = Symbol();
2123
- var regExpMetaChars = new Set(".\\+*[^]$()");
2124
- function compareKey(a, b) {
2125
- if (a.length === 1) {
2126
- return b.length === 1 ? a < b ? -1 : 1 : -1;
2127
- }
2128
- if (b.length === 1) {
2129
- return 1;
2130
- }
2131
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2132
- return 1;
2133
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2134
- return -1;
2135
- }
2136
- if (a === LABEL_REG_EXP_STR) {
2137
- return 1;
2138
- } else if (b === LABEL_REG_EXP_STR) {
2139
- return -1;
2140
- }
2141
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2142
- }
2143
- var Node = class {
2144
- #index;
2145
- #varIndex;
2146
- #children = /* @__PURE__ */ Object.create(null);
2147
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2148
- if (tokens.length === 0) {
2149
- if (this.#index !== void 0) {
2150
- throw PATH_ERROR;
2151
- }
2152
- if (pathErrorCheckOnly) {
2153
- return;
2154
- }
2155
- this.#index = index;
2156
- return;
2157
- }
2158
- const [token, ...restTokens] = tokens;
2159
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2160
- let node;
2161
- if (pattern) {
2162
- const name = pattern[1];
2163
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2164
- if (name && pattern[2]) {
2165
- if (regexpStr === ".*") {
2166
- throw PATH_ERROR;
2167
- }
2168
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2169
- if (/\((?!\?:)/.test(regexpStr)) {
2170
- throw PATH_ERROR;
2171
- }
2172
- }
2173
- node = this.#children[regexpStr];
2174
- if (!node) {
2175
- if (Object.keys(this.#children).some(
2176
- (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2177
- )) {
2178
- throw PATH_ERROR;
2179
- }
2180
- if (pathErrorCheckOnly) {
2181
- return;
2182
- }
2183
- node = this.#children[regexpStr] = new Node();
2184
- if (name !== "") {
2185
- node.#varIndex = context.varIndex++;
2186
- }
2187
- }
2188
- if (!pathErrorCheckOnly && name !== "") {
2189
- paramMap.push([name, node.#varIndex]);
2190
- }
2191
- } else {
2192
- node = this.#children[token];
2193
- if (!node) {
2194
- if (Object.keys(this.#children).some(
2195
- (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2196
- )) {
2197
- throw PATH_ERROR;
2198
- }
2199
- if (pathErrorCheckOnly) {
2200
- return;
2201
- }
2202
- node = this.#children[token] = new Node();
2203
- }
2204
- }
2205
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2206
- }
2207
- buildRegExpStr() {
2208
- const childKeys = Object.keys(this.#children).sort(compareKey);
2209
- const strList = childKeys.map((k) => {
2210
- const c = this.#children[k];
2211
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2212
- });
2213
- if (typeof this.#index === "number") {
2214
- strList.unshift(`#${this.#index}`);
2215
- }
2216
- if (strList.length === 0) {
2217
- return "";
2218
- }
2219
- if (strList.length === 1) {
2220
- return strList[0];
2221
- }
2222
- return "(?:" + strList.join("|") + ")";
2223
- }
2224
- };
2225
-
2226
- // ../../node_modules/hono/dist/router/reg-exp-router/trie.js
2227
- var Trie = class {
2228
- #context = { varIndex: 0 };
2229
- #root = new Node();
2230
- insert(path, index, pathErrorCheckOnly) {
2231
- const paramAssoc = [];
2232
- const groups = [];
2233
- for (let i = 0; ; ) {
2234
- let replaced = false;
2235
- path = path.replace(/\{[^}]+\}/g, (m) => {
2236
- const mark = `@\\${i}`;
2237
- groups[i] = [mark, m];
2238
- i++;
2239
- replaced = true;
2240
- return mark;
2241
- });
2242
- if (!replaced) {
2243
- break;
2244
- }
2245
- }
2246
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2247
- for (let i = groups.length - 1; i >= 0; i--) {
2248
- const [mark] = groups[i];
2249
- for (let j = tokens.length - 1; j >= 0; j--) {
2250
- if (tokens[j].indexOf(mark) !== -1) {
2251
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
2252
- break;
2253
- }
2254
- }
2255
- }
2256
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2257
- return paramAssoc;
2258
- }
2259
- buildRegExp() {
2260
- let regexp = this.#root.buildRegExpStr();
2261
- if (regexp === "") {
2262
- return [/^$/, [], []];
2263
- }
2264
- let captureIndex = 0;
2265
- const indexReplacementMap = [];
2266
- const paramReplacementMap = [];
2267
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2268
- if (handlerIndex !== void 0) {
2269
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
2270
- return "$()";
2271
- }
2272
- if (paramIndex !== void 0) {
2273
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2274
- return "";
2275
- }
2276
- return "";
2277
- });
2278
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2279
- }
2280
- };
2281
-
2282
- // ../../node_modules/hono/dist/router/reg-exp-router/router.js
2283
- var emptyParam = [];
2284
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2285
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2286
- function buildWildcardRegExp(path) {
2287
- return wildcardRegExpCache[path] ??= new RegExp(
2288
- path === "*" ? "" : `^${path.replace(
2289
- /\/\*$|([.\\+*[^\]$()])/g,
2290
- (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2291
- )}$`
2292
- );
2293
- }
2294
- function clearWildcardRegExpCache() {
2295
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2296
- }
2297
- function buildMatcherFromPreprocessedRoutes(routes) {
2298
- const trie = new Trie();
2299
- const handlerData = [];
2300
- if (routes.length === 0) {
2301
- return nullMatcher;
2302
- }
2303
- const routesWithStaticPathFlag = routes.map(
2304
- (route) => [!/\*|\/:/.test(route[0]), ...route]
2305
- ).sort(
2306
- ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2307
- );
2308
- const staticMap = /* @__PURE__ */ Object.create(null);
2309
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2310
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2311
- if (pathErrorCheckOnly) {
2312
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2313
- } else {
2314
- j++;
2315
- }
2316
- let paramAssoc;
2317
- try {
2318
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2319
- } catch (e) {
2320
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2321
- }
2322
- if (pathErrorCheckOnly) {
2323
- continue;
2324
- }
2325
- handlerData[j] = handlers.map(([h, paramCount]) => {
2326
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
2327
- paramCount -= 1;
2328
- for (; paramCount >= 0; paramCount--) {
2329
- const [key, value] = paramAssoc[paramCount];
2330
- paramIndexMap[key] = value;
2331
- }
2332
- return [h, paramIndexMap];
2333
- });
2334
- }
2335
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2336
- for (let i = 0, len = handlerData.length; i < len; i++) {
2337
- for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2338
- const map = handlerData[i][j]?.[1];
2339
- if (!map) {
2340
- continue;
2341
- }
2342
- const keys = Object.keys(map);
2343
- for (let k = 0, len3 = keys.length; k < len3; k++) {
2344
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
2345
- }
2346
- }
2347
- }
2348
- const handlerMap = [];
2349
- for (const i in indexReplacementMap) {
2350
- handlerMap[i] = handlerData[indexReplacementMap[i]];
2351
- }
2352
- return [regexp, handlerMap, staticMap];
2353
- }
2354
- function findMiddleware(middleware, path) {
2355
- if (!middleware) {
2356
- return void 0;
2357
- }
2358
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2359
- if (buildWildcardRegExp(k).test(path)) {
2360
- return [...middleware[k]];
2361
- }
2362
- }
2363
- return void 0;
2364
- }
2365
- var RegExpRouter = class {
2366
- name = "RegExpRouter";
2367
- #middleware;
2368
- #routes;
2369
- constructor() {
2370
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2371
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2372
- }
2373
- add(method, path, handler) {
2374
- const middleware = this.#middleware;
2375
- const routes = this.#routes;
2376
- if (!middleware || !routes) {
2377
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2378
- }
2379
- if (!middleware[method]) {
2380
- ;
2381
- [middleware, routes].forEach((handlerMap) => {
2382
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
2383
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2384
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2385
- });
2386
- });
2387
- }
2388
- if (path === "/*") {
2389
- path = "*";
2390
- }
2391
- const paramCount = (path.match(/\/:/g) || []).length;
2392
- if (/\*$/.test(path)) {
2393
- const re = buildWildcardRegExp(path);
2394
- if (method === METHOD_NAME_ALL) {
2395
- Object.keys(middleware).forEach((m) => {
2396
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2397
- });
2398
- } else {
2399
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2400
- }
2401
- Object.keys(middleware).forEach((m) => {
2402
- if (method === METHOD_NAME_ALL || method === m) {
2403
- Object.keys(middleware[m]).forEach((p) => {
2404
- re.test(p) && middleware[m][p].push([handler, paramCount]);
2405
- });
2406
- }
2407
- });
2408
- Object.keys(routes).forEach((m) => {
2409
- if (method === METHOD_NAME_ALL || method === m) {
2410
- Object.keys(routes[m]).forEach(
2411
- (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2412
- );
2413
- }
2414
- });
2415
- return;
2416
- }
2417
- const paths = checkOptionalParameter(path) || [path];
2418
- for (let i = 0, len = paths.length; i < len; i++) {
2419
- const path2 = paths[i];
2420
- Object.keys(routes).forEach((m) => {
2421
- if (method === METHOD_NAME_ALL || method === m) {
2422
- routes[m][path2] ||= [
2423
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2424
- ];
2425
- routes[m][path2].push([handler, paramCount - len + i + 1]);
2426
- }
2427
- });
2428
- }
2429
- }
2430
- match(method, path) {
2431
- clearWildcardRegExpCache();
2432
- const matchers = this.#buildAllMatchers();
2433
- this.match = (method2, path2) => {
2434
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2435
- const staticMatch = matcher[2][path2];
2436
- if (staticMatch) {
2437
- return staticMatch;
2438
- }
2439
- const match = path2.match(matcher[0]);
2440
- if (!match) {
2441
- return [[], emptyParam];
2442
- }
2443
- const index = match.indexOf("", 1);
2444
- return [matcher[1][index], match];
2445
- };
2446
- return this.match(method, path);
2447
- }
2448
- #buildAllMatchers() {
2449
- const matchers = /* @__PURE__ */ Object.create(null);
2450
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2451
- matchers[method] ||= this.#buildMatcher(method);
2452
- });
2453
- this.#middleware = this.#routes = void 0;
2454
- return matchers;
2455
- }
2456
- #buildMatcher(method) {
2457
- const routes = [];
2458
- let hasOwnRoute = method === METHOD_NAME_ALL;
2459
- [this.#middleware, this.#routes].forEach((r) => {
2460
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2461
- if (ownRoute.length !== 0) {
2462
- hasOwnRoute ||= true;
2463
- routes.push(...ownRoute);
2464
- } else if (method !== METHOD_NAME_ALL) {
2465
- routes.push(
2466
- ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2467
- );
2468
- }
2469
- });
2470
- if (!hasOwnRoute) {
2471
- return null;
2472
- } else {
2473
- return buildMatcherFromPreprocessedRoutes(routes);
2474
- }
2475
- }
2476
- };
2477
-
2478
- // ../../node_modules/hono/dist/router/smart-router/router.js
2479
- var SmartRouter = class {
2480
- name = "SmartRouter";
2481
- #routers = [];
2482
- #routes = [];
2483
- constructor(init) {
2484
- this.#routers = init.routers;
2485
- }
2486
- add(method, path, handler) {
2487
- if (!this.#routes) {
2488
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2489
- }
2490
- this.#routes.push([method, path, handler]);
2491
- }
2492
- match(method, path) {
2493
- if (!this.#routes) {
2494
- throw new Error("Fatal error");
2495
- }
2496
- const routers = this.#routers;
2497
- const routes = this.#routes;
2498
- const len = routers.length;
2499
- let i = 0;
2500
- let res;
2501
- for (; i < len; i++) {
2502
- const router = routers[i];
2503
- try {
2504
- for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2505
- router.add(...routes[i2]);
2506
- }
2507
- res = router.match(method, path);
2508
- } catch (e) {
2509
- if (e instanceof UnsupportedPathError) {
2510
- continue;
2511
- }
2512
- throw e;
2513
- }
2514
- this.match = router.match.bind(router);
2515
- this.#routers = [router];
2516
- this.#routes = void 0;
2517
- break;
2518
- }
2519
- if (i === len) {
2520
- throw new Error("Fatal error");
2521
- }
2522
- this.name = `SmartRouter + ${this.activeRouter.name}`;
2523
- return res;
2524
- }
2525
- get activeRouter() {
2526
- if (this.#routes || this.#routers.length !== 1) {
2527
- throw new Error("No active router has been determined yet.");
2528
- }
2529
- return this.#routers[0];
2530
- }
2531
- };
2532
-
2533
- // ../../node_modules/hono/dist/router/trie-router/node.js
2534
- var emptyParams = /* @__PURE__ */ Object.create(null);
2535
- var Node2 = class {
2536
- #methods;
2537
- #children;
2538
- #patterns;
2539
- #order = 0;
2540
- #params = emptyParams;
2541
- constructor(method, handler, children) {
2542
- this.#children = children || /* @__PURE__ */ Object.create(null);
2543
- this.#methods = [];
2544
- if (method && handler) {
2545
- const m = /* @__PURE__ */ Object.create(null);
2546
- m[method] = { handler, possibleKeys: [], score: 0 };
2547
- this.#methods = [m];
2548
- }
2549
- this.#patterns = [];
2550
- }
2551
- insert(method, path, handler) {
2552
- this.#order = ++this.#order;
2553
- let curNode = this;
2554
- const parts = splitRoutingPath(path);
2555
- const possibleKeys = [];
2556
- for (let i = 0, len = parts.length; i < len; i++) {
2557
- const p = parts[i];
2558
- const nextP = parts[i + 1];
2559
- const pattern = getPattern(p, nextP);
2560
- const key = Array.isArray(pattern) ? pattern[0] : p;
2561
- if (key in curNode.#children) {
2562
- curNode = curNode.#children[key];
2563
- if (pattern) {
2564
- possibleKeys.push(pattern[1]);
2565
- }
2566
- continue;
2567
- }
2568
- curNode.#children[key] = new Node2();
2569
- if (pattern) {
2570
- curNode.#patterns.push(pattern);
2571
- possibleKeys.push(pattern[1]);
2572
- }
2573
- curNode = curNode.#children[key];
2574
- }
2575
- curNode.#methods.push({
2576
- [method]: {
2577
- handler,
2578
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2579
- score: this.#order
2580
- }
2581
- });
2582
- return curNode;
2583
- }
2584
- #getHandlerSets(node, method, nodeParams, params) {
2585
- const handlerSets = [];
2586
- for (let i = 0, len = node.#methods.length; i < len; i++) {
2587
- const m = node.#methods[i];
2588
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
2589
- const processedSet = {};
2590
- if (handlerSet !== void 0) {
2591
- handlerSet.params = /* @__PURE__ */ Object.create(null);
2592
- handlerSets.push(handlerSet);
2593
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
2594
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2595
- const key = handlerSet.possibleKeys[i2];
2596
- const processed = processedSet[handlerSet.score];
2597
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2598
- processedSet[handlerSet.score] = true;
2599
- }
2600
- }
2601
- }
2602
- }
2603
- return handlerSets;
2604
- }
2605
- search(method, path) {
2606
- const handlerSets = [];
2607
- this.#params = emptyParams;
2608
- const curNode = this;
2609
- let curNodes = [curNode];
2610
- const parts = splitPath(path);
2611
- const curNodesQueue = [];
2612
- for (let i = 0, len = parts.length; i < len; i++) {
2613
- const part = parts[i];
2614
- const isLast = i === len - 1;
2615
- const tempNodes = [];
2616
- for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2617
- const node = curNodes[j];
2618
- const nextNode = node.#children[part];
2619
- if (nextNode) {
2620
- nextNode.#params = node.#params;
2621
- if (isLast) {
2622
- if (nextNode.#children["*"]) {
2623
- handlerSets.push(
2624
- ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
2625
- );
2626
- }
2627
- handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
2628
- } else {
2629
- tempNodes.push(nextNode);
2630
- }
2631
- }
2632
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2633
- const pattern = node.#patterns[k];
2634
- const params = node.#params === emptyParams ? {} : { ...node.#params };
2635
- if (pattern === "*") {
2636
- const astNode = node.#children["*"];
2637
- if (astNode) {
2638
- handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
2639
- astNode.#params = params;
2640
- tempNodes.push(astNode);
2641
- }
2642
- continue;
2643
- }
2644
- const [key, name, matcher] = pattern;
2645
- if (!part && !(matcher instanceof RegExp)) {
2646
- continue;
2647
- }
2648
- const child = node.#children[key];
2649
- const restPathString = parts.slice(i).join("/");
2650
- if (matcher instanceof RegExp) {
2651
- const m = matcher.exec(restPathString);
2652
- if (m) {
2653
- params[name] = m[0];
2654
- handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
2655
- if (Object.keys(child.#children).length) {
2656
- child.#params = params;
2657
- const componentCount = m[0].match(/\//)?.length ?? 0;
2658
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
2659
- targetCurNodes.push(child);
2660
- }
2661
- continue;
2662
- }
2663
- }
2664
- if (matcher === true || matcher.test(part)) {
2665
- params[name] = part;
2666
- if (isLast) {
2667
- handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
2668
- if (child.#children["*"]) {
2669
- handlerSets.push(
2670
- ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
2671
- );
2672
- }
2673
- } else {
2674
- child.#params = params;
2675
- tempNodes.push(child);
2676
- }
2677
- }
2678
- }
2679
- }
2680
- curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
2681
- }
2682
- if (handlerSets.length > 1) {
2683
- handlerSets.sort((a, b) => {
2684
- return a.score - b.score;
2685
- });
2686
- }
2687
- return [handlerSets.map(({ handler, params }) => [handler, params])];
2688
- }
2689
- };
2690
-
2691
- // ../../node_modules/hono/dist/router/trie-router/router.js
2692
- var TrieRouter = class {
2693
- name = "TrieRouter";
2694
- #node;
2695
- constructor() {
2696
- this.#node = new Node2();
2697
- }
2698
- add(method, path, handler) {
2699
- const results = checkOptionalParameter(path);
2700
- if (results) {
2701
- for (let i = 0, len = results.length; i < len; i++) {
2702
- this.#node.insert(method, results[i], handler);
2703
- }
2704
- return;
2705
- }
2706
- this.#node.insert(method, path, handler);
2707
- }
2708
- match(method, path) {
2709
- return this.#node.search(method, path);
2710
- }
2711
- };
2712
-
2713
- // ../../node_modules/hono/dist/hono.js
2714
- var Hono2 = class extends Hono {
2715
- constructor(options = {}) {
2716
- super(options);
2717
- this.router = options.router ?? new SmartRouter({
2718
- routers: [new RegExpRouter(), new TrieRouter()]
2719
- });
2720
- }
2721
- };
2722
-
2723
- // ../../node_modules/hono/dist/http-exception.js
2724
- var HTTPException = class extends Error {
2725
- res;
2726
- status;
2727
- constructor(status = 500, options) {
2728
- super(options?.message, { cause: options?.cause });
2729
- this.res = options?.res;
2730
- this.status = status;
2731
- }
2732
- getResponse() {
2733
- if (this.res) {
2734
- const newResponse = new Response(this.res.body, {
2735
- status: this.status,
2736
- headers: this.res.headers
2737
- });
2738
- return newResponse;
2739
- }
2740
- return new Response(this.message, {
2741
- status: this.status
2742
- });
2743
- }
2744
- };
2745
-
2746
- // src/server.ts
689
+ var import_ubiquity_os_logger4 = require("@ubiquity-os/ubiquity-os-logger");
690
+ var import_hono = require("hono");
691
+ var import_adapter2 = require("hono/adapter");
692
+ var import_http_exception = require("hono/http-exception");
2747
693
  async function handleError2(context, pluginOptions, error) {
2748
694
  console.error(error);
2749
695
  const loggerError = transformError(context, error);
2750
696
  if (pluginOptions.postCommentOnError && loggerError) {
2751
697
  await context.commentHandler.postComment(context, loggerError);
2752
698
  }
2753
- throw new HTTPException(500, { message: "Unexpected error" });
699
+ throw new import_http_exception.HTTPException(500, { message: "Unexpected error" });
2754
700
  }
2755
701
  function createPlugin(handler, manifest, options) {
2756
702
  const pluginOptions = getPluginOptions(options);
2757
- const app = new Hono2();
703
+ const app = new import_hono.Hono();
2758
704
  app.get("/manifest.json", (ctx) => {
2759
705
  return ctx.json(manifest);
2760
706
  });
2761
707
  app.post("/", async function appPost(ctx) {
2762
708
  if (ctx.req.header("content-type") !== "application/json") {
2763
- throw new HTTPException(400, { message: "Content-Type must be application/json" });
709
+ throw new import_http_exception.HTTPException(400, { message: "Content-Type must be application/json" });
2764
710
  }
2765
711
  const body = await ctx.req.json();
2766
712
  const inputSchemaErrors = [...import_value4.Value.Errors(inputSchema, body)];
2767
713
  if (inputSchemaErrors.length) {
2768
714
  console.dir(inputSchemaErrors, { depth: null });
2769
- throw new HTTPException(400, { message: "Invalid body" });
715
+ throw new import_http_exception.HTTPException(400, { message: "Invalid body" });
2770
716
  }
2771
717
  const signature = body.signature;
2772
718
  if (!pluginOptions.bypassSignatureVerification && !await verifySignature(pluginOptions.kernelPublicKey, body, signature)) {
2773
- throw new HTTPException(400, { message: "Invalid signature" });
719
+ throw new import_http_exception.HTTPException(400, { message: "Invalid signature" });
2774
720
  }
2775
721
  const inputs = import_value4.Value.Decode(inputSchema, body);
2776
722
  let config2;
@@ -2784,20 +730,20 @@ function createPlugin(handler, manifest, options) {
2784
730
  } else {
2785
731
  config2 = inputs.settings;
2786
732
  }
2787
- let env2;
2788
- const honoEnvironment = env(ctx);
733
+ let env;
734
+ const honoEnvironment = (0, import_adapter2.env)(ctx);
2789
735
  if (pluginOptions.envSchema) {
2790
736
  try {
2791
- env2 = import_value4.Value.Decode(pluginOptions.envSchema, import_value4.Value.Default(pluginOptions.envSchema, honoEnvironment));
737
+ env = import_value4.Value.Decode(pluginOptions.envSchema, import_value4.Value.Default(pluginOptions.envSchema, honoEnvironment));
2792
738
  } catch (e) {
2793
739
  console.dir(...import_value4.Value.Errors(pluginOptions.envSchema, honoEnvironment), { depth: null });
2794
740
  throw e;
2795
741
  }
2796
742
  } else {
2797
- env2 = ctx.env;
743
+ env = ctx.env;
2798
744
  }
2799
745
  const workerName = new URL(inputs.ref).hostname.split(".")[0];
2800
- PluginRuntimeInfo.getInstance({ ...env2, CLOUDFLARE_WORKER_NAME: workerName });
746
+ PluginRuntimeInfo.getInstance({ ...env, CLOUDFLARE_WORKER_NAME: workerName });
2801
747
  const command = getCommand(inputs, pluginOptions);
2802
748
  const context = {
2803
749
  eventName: inputs.eventName,
@@ -2807,8 +753,8 @@ function createPlugin(handler, manifest, options) {
2807
753
  ubiquityKernelToken: inputs.ubiquityKernelToken,
2808
754
  octokit: new customOctokit({ auth: inputs.authToken }),
2809
755
  config: config2,
2810
- env: env2,
2811
- logger: new Logs(pluginOptions.logLevel),
756
+ env,
757
+ logger: new import_ubiquity_os_logger4.Logs(pluginOptions.logLevel),
2812
758
  commentHandler: new CommentHandler()
2813
759
  };
2814
760
  try {
@@ -2921,6 +867,10 @@ async function fetchWithRetry(url, options, maxRetries) {
2921
867
  throw error;
2922
868
  } catch (error) {
2923
869
  lastError = error;
870
+ const status = typeof error.status === "number" ? error.status : void 0;
871
+ if (typeof status === "number" && status < 500) {
872
+ throw error;
873
+ }
2924
874
  if (attempt >= maxRetries) throw error;
2925
875
  await sleep(getRetryDelayMs(attempt));
2926
876
  attempt += 1;
@@ -2996,6 +946,13 @@ function parseEventData(data) {
2996
946
  try {
2997
947
  return JSON.parse(data);
2998
948
  } catch (error) {
949
+ if (data.includes("\n")) {
950
+ const collapsed = data.replace(/\n/g, EMPTY_STRING);
951
+ try {
952
+ return JSON.parse(collapsed);
953
+ } catch {
954
+ }
955
+ }
2999
956
  const message = error instanceof Error ? error.message : String(error);
3000
957
  const preview = data.length > 200 ? `${data.slice(0, 200)}...` : data;
3001
958
  throw new Error(`LLM stream parse error: ${message}. Data: ${preview}`);