@stats-organization/github-readme-stats-core 2.1.4 → 2.1.5

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 (77) hide show
  1. package/build/api/gist.d.ts.map +1 -1
  2. package/build/api/gist.js +34 -0
  3. package/build/api/index.d.ts.map +1 -1
  4. package/build/api/index.js +18 -0
  5. package/build/api/pin.d.ts.map +1 -1
  6. package/build/api/pin.js +17 -0
  7. package/build/api/top-langs.d.ts.map +1 -1
  8. package/build/api/top-langs.js +36 -4
  9. package/build/api/wakatime.d.ts.map +1 -1
  10. package/build/api/wakatime.js +34 -0
  11. package/build/calculateRank.d.ts +12 -11
  12. package/build/calculateRank.d.ts.map +1 -1
  13. package/build/calculateRank.js +18 -18
  14. package/build/cards/repo.d.ts.map +1 -1
  15. package/build/cards/repo.js +29 -20
  16. package/build/cards/stats.d.ts +4 -2
  17. package/build/cards/stats.d.ts.map +1 -1
  18. package/build/cards/stats.js +21 -8
  19. package/build/cards/top-languages.d.ts.map +1 -1
  20. package/build/cards/top-languages.js +39 -11
  21. package/build/cards/wakatime.d.ts.map +1 -1
  22. package/build/cards/wakatime.js +29 -8
  23. package/build/common/Card.d.ts +9 -3
  24. package/build/common/Card.d.ts.map +1 -1
  25. package/build/common/Card.js +47 -19
  26. package/build/common/color.d.ts +42 -8
  27. package/build/common/color.d.ts.map +1 -1
  28. package/build/common/color.js +62 -13
  29. package/build/common/html.js +1 -1
  30. package/build/common/http.d.ts +13 -4
  31. package/build/common/http.d.ts.map +1 -1
  32. package/build/common/http.js +3 -3
  33. package/build/common/languageColors.json +9 -1
  34. package/build/common/ops.d.ts +30 -29
  35. package/build/common/ops.d.ts.map +1 -1
  36. package/build/common/ops.js +32 -37
  37. package/build/common/render.d.ts +115 -111
  38. package/build/common/render.d.ts.map +1 -1
  39. package/build/common/render.js +138 -87
  40. package/build/common/retryer.d.ts +14 -6
  41. package/build/common/retryer.d.ts.map +1 -1
  42. package/build/common/retryer.js +1 -0
  43. package/build/fetchers/gist.d.ts +6 -21
  44. package/build/fetchers/gist.d.ts.map +1 -1
  45. package/build/fetchers/gist.js +30 -35
  46. package/build/fetchers/repo.js +1 -1
  47. package/build/fetchers/stats.d.ts.map +1 -1
  48. package/build/fetchers/stats.js +0 -1
  49. package/build/fetchers/types.d.ts +126 -0
  50. package/build/fetchers/types.d.ts.map +1 -0
  51. package/build/fetchers/types.js +1 -0
  52. package/package.json +4 -4
  53. package/src/_emoji-name-map.d.ts +10 -0
  54. package/src/api/gist.js +36 -0
  55. package/src/api/index.js +19 -0
  56. package/src/api/pin.js +18 -0
  57. package/src/api/top-langs.js +38 -4
  58. package/src/api/wakatime.js +36 -0
  59. package/src/{calculateRank.js → calculateRank.ts} +29 -19
  60. package/src/cards/repo.js +30 -20
  61. package/src/cards/stats.js +22 -8
  62. package/src/cards/top-languages.js +49 -11
  63. package/src/cards/wakatime.js +33 -8
  64. package/src/common/Card.ts +51 -16
  65. package/src/common/color.ts +85 -22
  66. package/src/common/html.ts +1 -1
  67. package/src/common/http.ts +31 -0
  68. package/src/common/languageColors.json +9 -1
  69. package/src/common/{ops.js → ops.ts} +48 -50
  70. package/src/common/{render.js → render.ts} +208 -96
  71. package/src/common/retryer.ts +18 -10
  72. package/src/fetchers/gist.ts +136 -0
  73. package/src/fetchers/repo.js +1 -1
  74. package/src/fetchers/stats.js +0 -1
  75. package/src/common/http.js +0 -19
  76. package/src/fetchers/gist.js +0 -112
  77. /package/src/fetchers/{types.d.ts → types.ts} +0 -0
@@ -1,4 +1,4 @@
1
- import { getCardColors } from "./color.js";
1
+ import { getCardColors, isPrefixedHexColor } from "./color.js";
2
2
  import { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from "./error.js";
3
3
  import { encodeHTML } from "./html.js";
4
4
  import { clampValue } from "./ops.js";
@@ -7,14 +7,30 @@ import { clampValue } from "./ops.js";
7
7
  * Auto layout utility, allows us to layout things vertically or horizontally with
8
8
  * proper gaping.
9
9
  *
10
- * @param {object} props Function properties.
11
- * @param {string[]} props.items Array of items to layout.
12
- * @param {number} props.gap Gap between items.
13
- * @param {"column" | "row"=} props.direction Direction to layout items.
14
- * @param {number[]=} props.sizes Array of sizes for each item.
15
- * @returns {string[]} Array of items with proper layout.
10
+ * The caller must ensure that the passed `items` are properly sanitized!
11
+ *
12
+ * @param props Function properties.
13
+ * @param props.items Array of sanitized items to layout.
14
+ * @param props.gap Gap between items.
15
+ * @param props.direction Direction to layout items.
16
+ * @param props.sizes Array of sizes for each item.
17
+ * @returns Array of items with proper layout.
16
18
  */
17
- const flexLayout = ({ items, gap, direction, sizes = [] }) => {
19
+ const flexLayout = ({
20
+ items,
21
+ gap,
22
+ direction,
23
+ sizes = [],
24
+ }: {
25
+ items: Array<string>;
26
+ gap: number;
27
+ direction?: "column" | "row";
28
+ sizes?: Array<number>;
29
+ }): Array<string> => {
30
+ if (sizes.some((size) => !Number.isFinite(size))) {
31
+ throw new Error("flexLayout: `sizes` must contain only numbers");
32
+ }
33
+
18
34
  let lastSize = 0;
19
35
  // filter() for filtering out empty strings
20
36
  return items.filter(Boolean).map((item, i) => {
@@ -31,15 +47,19 @@ const flexLayout = ({ items, gap, direction, sizes = [] }) => {
31
47
  /**
32
48
  * Creates a node to display the primary programming language of the repository/gist.
33
49
  *
34
- * @param {string} langName Language name.
35
- * @param {string} langColor Language color.
36
- * @returns {string} Language display SVG object.
50
+ * @param langName Language name.
51
+ * @param langColor Language color.
52
+ * @returns Language display SVG object.
37
53
  */
38
- const createLanguageNode = (langName, langColor) => {
54
+ const createLanguageNode = (langName: string, langColor: string): string => {
55
+ if (!isPrefixedHexColor(langColor)) {
56
+ throw new Error(`Invalid language color: "${langColor}"`);
57
+ }
58
+
39
59
  return `
40
60
  <g data-testid="primary-lang">
41
61
  <circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" />
42
- <text data-testid="lang-name" class="gray" x="15">${langName}</text>
62
+ <text data-testid="lang-name" class="gray" x="15">${encodeHTML(langName)}</text>
43
63
  </g>
44
64
  `;
45
65
  };
@@ -47,15 +67,15 @@ const createLanguageNode = (langName, langColor) => {
47
67
  /**
48
68
  * Create a node to indicate progress in percentage along a horizontal line.
49
69
  *
50
- * @param {Object} params Object that contains the createProgressNode parameters.
51
- * @param {number} params.x X-axis position.
52
- * @param {number} params.y Y-axis position.
53
- * @param {number} params.width Width of progress bar.
54
- * @param {string} params.color Progress color.
55
- * @param {number} params.progress Progress value.
56
- * @param {string} params.progressBarBackgroundColor Progress bar bg color.
57
- * @param {number} params.delay Delay before animation starts.
58
- * @returns {string} Progress node.
70
+ * @param params Object that contains the createProgressNode parameters.
71
+ * @param params.x X-axis position.
72
+ * @param params.y Y-axis position.
73
+ * @param params.width Width of progress bar.
74
+ * @param params.color Progress color.
75
+ * @param params.progress Progress value.
76
+ * @param params.progressBarBackgroundColor Progress bar bg color.
77
+ * @param params.delay Delay before animation starts.
78
+ * @returns Progress node.
59
79
  */
60
80
  const createProgressNode = ({
61
81
  x,
@@ -65,7 +85,36 @@ const createProgressNode = ({
65
85
  progress,
66
86
  progressBarBackgroundColor,
67
87
  delay,
68
- }) => {
88
+ }: {
89
+ x: number;
90
+ y: number;
91
+ width: number;
92
+ color: string;
93
+ progress: number;
94
+ progressBarBackgroundColor: string;
95
+ delay: number;
96
+ }): string => {
97
+ if (!isPrefixedHexColor(color)) {
98
+ throw new Error(`Invalid progress color: "${color}"`);
99
+ }
100
+ if (!isPrefixedHexColor(progressBarBackgroundColor)) {
101
+ throw new Error(
102
+ `Invalid progress bar background color: "${progressBarBackgroundColor}"`,
103
+ );
104
+ }
105
+ if (!Number.isFinite(width)) {
106
+ throw new Error(`Invalid width: "${width}"`);
107
+ }
108
+ if (!Number.isFinite(x)) {
109
+ throw new Error(`Invalid x: "${x}"`);
110
+ }
111
+ if (!Number.isFinite(y)) {
112
+ throw new Error(`Invalid y: "${y}"`);
113
+ }
114
+ if (!Number.isFinite(delay)) {
115
+ throw new Error(`Invalid delay: "${delay}"`);
116
+ }
117
+
69
118
  const progressPercentage = clampValue(progress, 2, 100);
70
119
 
71
120
  return `
@@ -89,16 +138,16 @@ const createProgressNode = ({
89
138
  * native, font-aware wrapping. Content overflowing `lineCount` lines is
90
139
  * clipped (with an ellipsis on the last visible line) by CSS line-clamp.
91
140
  *
92
- * @param {object} props Function properties.
93
- * @param {string} props.text Text to render (will be HTML-encoded).
94
- * @param {number} props.x X position of the foreignObject.
95
- * @param {number} props.y Y position of the foreignObject.
96
- * @param {number} props.width Width of the wrap box.
97
- * @param {number} props.height Height of the wrap box.
98
- * @param {number} props.lineCount Maximum number of lines to display.
99
- * @param {string} props.className CSS class applied to the inner element.
100
- * @param {string=} props.testId Optional test id for the inner element.
101
- * @returns {string} foreignObject SVG node.
141
+ * @param props Function properties.
142
+ * @param props.text Text to render (will be HTML-encoded).
143
+ * @param props.x X position of the foreignObject.
144
+ * @param props.y Y position of the foreignObject.
145
+ * @param props.width Width of the wrap box.
146
+ * @param props.height Height of the wrap box.
147
+ * @param props.lineCount Maximum number of lines to display.
148
+ * @param props.className CSS class applied to the inner element.
149
+ * @param props.testId Optional test id for the inner element.
150
+ * @returns foreignObject SVG node.
102
151
  */
103
152
  const wrappedTextNode = ({
104
153
  text,
@@ -109,11 +158,36 @@ const wrappedTextNode = ({
109
158
  lineCount,
110
159
  className,
111
160
  testId,
112
- }) => {
113
- const testIdAttr = testId ? ` data-testid="${testId}"` : "";
161
+ }: {
162
+ text: string;
163
+ x: number;
164
+ y: number;
165
+ width: number;
166
+ height: number;
167
+ lineCount: number;
168
+ className: string;
169
+ testId?: string;
170
+ }): string => {
171
+ if (!Number.isFinite(x)) {
172
+ throw new Error(`Invalid x: "${x}"`);
173
+ }
174
+ if (!Number.isFinite(y)) {
175
+ throw new Error(`Invalid y: "${y}"`);
176
+ }
177
+ if (!Number.isFinite(width)) {
178
+ throw new Error(`Invalid width: "${width}"`);
179
+ }
180
+ if (!Number.isFinite(height)) {
181
+ throw new Error(`Invalid height: "${height}"`);
182
+ }
183
+ if (!Number.isFinite(lineCount)) {
184
+ throw new Error(`Invalid lineCount: "${lineCount}"`);
185
+ }
186
+
187
+ const testIdAttr = testId ? ` data-testid="${encodeHTML(testId)}"` : "";
114
188
  return `
115
189
  <foreignObject x="${x}" y="${y}" width="${width}" height="${height}">
116
- <div xmlns="http://www.w3.org/1999/xhtml" class="${className}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(
190
+ <div xmlns="http://www.w3.org/1999/xhtml" class="${encodeHTML(className)}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(
117
191
  text,
118
192
  )}</div>
119
193
  </foreignObject>
@@ -126,37 +200,55 @@ const wrappedTextNode = ({
126
200
  * browser handles wrapping and the line count is taken from the `--lines`
127
201
  * custom property set on the element.
128
202
  *
129
- * @param {string} color Text color (CSS `color` property).
130
- * @returns {string} CSS rules block (without the surrounding selector).
203
+ * @param color Text color (CSS `color` property).
204
+ * @returns CSS rules block (without the surrounding selector).
131
205
  */
132
- const wrappedTextStyles = (color) => `
133
- color: ${color};
134
- margin: 0;
135
- line-height: 1.2;
136
- overflow-wrap: anywhere;
137
- word-break: break-word;
138
- display: -webkit-box;
139
- -webkit-box-orient: vertical;
140
- -webkit-line-clamp: var(--lines);
141
- line-clamp: var(--lines);
142
- overflow: hidden;
143
- text-overflow: ellipsis;
144
- padding-bottom: 0.15em;
145
- `;
206
+ const wrappedTextStyles = (color: string): string => {
207
+ if (!isPrefixedHexColor(color)) {
208
+ throw new Error(`Invalid text color: "${color}"`);
209
+ }
210
+
211
+ return `
212
+ color: ${color};
213
+ margin: 0;
214
+ line-height: 1.2;
215
+ overflow-wrap: anywhere;
216
+ word-break: break-word;
217
+ display: -webkit-box;
218
+ -webkit-box-orient: vertical;
219
+ -webkit-line-clamp: var(--lines);
220
+ line-clamp: var(--lines);
221
+ overflow: hidden;
222
+ text-overflow: ellipsis;
223
+ padding-bottom: 0.15em;
224
+ `;
225
+ };
146
226
 
147
227
  /**
148
228
  * Creates an icon with label to display repository/gist stats like forks, stars, etc.
149
229
  *
150
- * @param {string} icon The icon to display.
151
- * @param {number|string} label The label to display.
152
- * @param {string} testid The testid to assign to the label.
153
- * @param {number} iconSize The size of the icon.
154
- * @returns {string} Icon with label SVG object.
230
+ * The caller must ensure that the passed `icon` is properly sanitized!
231
+ *
232
+ * @param icon The sanitized icon to display.
233
+ * @param label The label to display.
234
+ * @param testid The testid to assign to the label.
235
+ * @param iconSize The size of the icon.
236
+ * @returns Icon with label SVG object.
155
237
  */
156
- const iconWithLabel = (icon, label, testid, iconSize) => {
238
+ const iconWithLabel = (
239
+ icon: string,
240
+ label: number | string,
241
+ testid: string,
242
+ iconSize: number,
243
+ ): string => {
157
244
  if (typeof label === "number" && label <= 0) {
158
245
  return "";
159
246
  }
247
+
248
+ if (!Number.isFinite(iconSize)) {
249
+ throw new Error(`Invalid iconSize: "${iconSize}"`);
250
+ }
251
+
160
252
  const iconSvg = `
161
253
  <svg
162
254
  class="icon"
@@ -169,7 +261,7 @@ const iconWithLabel = (icon, label, testid, iconSize) => {
169
261
  ${icon}
170
262
  </svg>
171
263
  `;
172
- const text = `<text data-testid="${testid}" class="gray">${label}</text>`;
264
+ const text = `<text data-testid="${encodeHTML(testid)}" class="gray">${encodeHTML(String(label))}</text>`;
173
265
  return flexLayout({ items: [iconSvg, text], gap: 20 }).join("");
174
266
  };
175
267
 
@@ -184,23 +276,34 @@ const UPSTREAM_API_ERRORS = [
184
276
  /**
185
277
  * Renders error message on the card.
186
278
  *
187
- * @param {object} args Function arguments.
188
- * @param {string} args.message Main error message.
189
- * @param {string} [args.secondaryMessage=""] The secondary error message.
190
- * @param {object} [args.renderOptions={}] Render options.
191
- * @param {string=} args.renderOptions.title_color Card title color.
192
- * @param {string=} args.renderOptions.text_color Card text color.
193
- * @param {string=} args.renderOptions.bg_color Card background color.
194
- * @param {string=} args.renderOptions.border_color Card border color.
195
- * @param {Parameters<typeof getCardColors>[0]["theme"]=} args.renderOptions.theme Card theme.
196
- * @param {boolean=} args.renderOptions.show_repo_link Whether to show repo link or not.
197
- * @returns {string} The SVG markup.
279
+ * @param args Function arguments.
280
+ * @param args.message Main error message.
281
+ * @param args.secondaryMessage The secondary error message.
282
+ * @param args.renderOptions Render options.
283
+ * @param args.renderOptions.title_color Card title color.
284
+ * @param args.renderOptions.text_color Card text color.
285
+ * @param args.renderOptions.bg_color Card background color.
286
+ * @param args.renderOptions.border_color Card border color.
287
+ * @param args.renderOptions.theme Card theme.
288
+ * @param args.renderOptions.show_repo_link Whether to show repo link or not.
289
+ * @returns The SVG markup.
198
290
  */
199
291
  const renderError = ({
200
292
  message,
201
293
  secondaryMessage = "",
202
294
  renderOptions = {},
203
- }) => {
295
+ }: {
296
+ message: string;
297
+ secondaryMessage?: string;
298
+ renderOptions?: {
299
+ title_color?: string;
300
+ text_color?: string;
301
+ bg_color?: string;
302
+ border_color?: string;
303
+ theme?: string;
304
+ show_repo_link?: boolean;
305
+ };
306
+ }): string => {
204
307
  const {
205
308
  title_color,
206
309
  text_color,
@@ -222,7 +325,7 @@ const renderError = ({
222
325
  });
223
326
 
224
327
  return `
225
- <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${bgColor}" xmlns="http://www.w3.org/2000/svg">
328
+ <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${String(bgColor)}" xmlns="http://www.w3.org/2000/svg">
226
329
  <style>
227
330
  .text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor} }
228
331
  .small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
@@ -230,7 +333,7 @@ const renderError = ({
230
333
  </style>
231
334
  <rect x="0.5" y="0.5" width="${
232
335
  ERROR_CARD_LENGTH - 1
233
- }" height="99%" rx="4.5" fill="${bgColor}" stroke="${borderColor}"/>
336
+ }" height="99%" rx="4.5" fill="${String(bgColor)}" stroke="${borderColor}"/>
234
337
  <text x="25" y="45" class="text">Something went wrong!${
235
338
  UPSTREAM_API_ERRORS.includes(secondaryMessage) || !show_repo_link
236
339
  ? ""
@@ -238,7 +341,7 @@ const renderError = ({
238
341
  }</text>
239
342
  <text data-testid="message" x="25" y="55" class="text small">
240
343
  <tspan x="25" dy="18">${encodeHTML(message)}</tspan>
241
- <tspan x="25" dy="18" class="gray">${secondaryMessage}</tspan>
344
+ <tspan x="25" dy="18" class="gray">${encodeHTML(secondaryMessage)}</tspan>
242
345
  </text>
243
346
  </svg>
244
347
  `;
@@ -248,11 +351,11 @@ const renderError = ({
248
351
  * Retrieve text length based on Segoe UI font.
249
352
  *
250
353
  * @see https://stackoverflow.com/a/48172630/10629172
251
- * @param {string} str String to measure.
252
- * @param {number} fontSize Font size.
253
- * @returns {number} Text length.
354
+ * @param str String to measure.
355
+ * @param fontSize Font size.
356
+ * @returns Text length.
254
357
  */
255
- const measureText = (str, fontSize = 10) => {
358
+ const measureText = (str: string, fontSize = 10): number => {
256
359
  // prettier-ignore
257
360
  const widths = [
258
361
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -304,7 +407,7 @@ const measureText = (str, fontSize = 10) => {
304
407
  return 1;
305
408
  }
306
409
  if (c.charCodeAt(0) < widths.length) {
307
- return widths[c.charCodeAt(0)];
410
+ return widths[c.charCodeAt(0)] ?? avg;
308
411
  } else {
309
412
  return avg;
310
413
  }
@@ -320,12 +423,16 @@ const measureText = (str, fontSize = 10) => {
320
423
  * The browser still does the real wrap inside the foreignObject; this is only
321
424
  * used to size the SVG.
322
425
  *
323
- * @param {string} text Text to split.
324
- * @param {number} fontSize Font size in px (matches `measureText`).
325
- * @param {number} maxWidth Available wrap width in px.
326
- * @returns {string[]} Estimated wrapped lines.
426
+ * @param text Text to split.
427
+ * @param fontSize Font size in px (matches `measureText`).
428
+ * @param maxWidth Available wrap width in px.
429
+ * @returns Estimated wrapped lines.
327
430
  */
328
- const splitWrappedText = (text, fontSize, maxWidth) => {
431
+ const splitWrappedText = (
432
+ text: string,
433
+ fontSize: number,
434
+ maxWidth: number,
435
+ ): Array<string> => {
329
436
  if (!text) {
330
437
  return [];
331
438
  }
@@ -340,15 +447,15 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
340
447
  // Korean Hangul (U+AC00–U+D7AF) is intentionally NOT in the CJK range
341
448
  // because Korean wraps at word boundaries by default in HTML.
342
449
  // ASCII whitespace is collapsed to a single space per CSS `white-space: normal;`
343
- text = text.replace(/[\t\n\r ]+/g, " ");
344
- const tokens = text.match(
450
+ const normalizedText = text.replace(/[\t\n\r ]+/g, " ");
451
+ const tokens = normalizedText.match(
345
452
  /\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g,
346
453
  );
347
454
  if (!tokens) {
348
455
  return [];
349
456
  }
350
457
 
351
- const takeFittingSegment = (token, availableWidth) => {
458
+ const takeFittingSegment = (token: string, availableWidth: number) => {
352
459
  const characters = token.split("");
353
460
  let segment = "";
354
461
  let width = 0;
@@ -377,7 +484,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
377
484
  if (currentWidth === 0) {
378
485
  continue;
379
486
  }
380
- lines[lines.length - 1] += token;
487
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + token;
381
488
  currentWidth += measureText(token, fontSize);
382
489
  continue;
383
490
  }
@@ -387,7 +494,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
387
494
  while (remaining) {
388
495
  const w = measureText(remaining, fontSize);
389
496
  if (currentWidth + w <= maxWidth) {
390
- lines[lines.length - 1] += remaining;
497
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + remaining;
391
498
  currentWidth += w;
392
499
  break;
393
500
  }
@@ -400,7 +507,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
400
507
 
401
508
  // An atom wider than the box wraps mid-glyph (overflow-wrap: anywhere).
402
509
  const { segment, width } = takeFittingSegment(remaining, maxWidth);
403
- lines[lines.length - 1] += segment;
510
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + segment;
404
511
  currentWidth = width;
405
512
  remaining = remaining.slice(segment.length);
406
513
  }
@@ -413,13 +520,18 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
413
520
  * Estimate how many lines a string will wrap to when laid out greedily at the
414
521
  * given font size inside a box of width `maxWidth`, capped at `maxLines`.
415
522
  *
416
- * @param {string} text Text to estimate.
417
- * @param {number} fontSize Font size in px (matches `measureText`).
418
- * @param {number} maxWidth Available wrap width in px.
419
- * @param {number} maxLines Cap on the returned line count.
420
- * @returns {number} Estimated line count, at least 1, at most `maxLines`.
523
+ * @param text Text to estimate.
524
+ * @param fontSize Font size in px (matches `measureText`).
525
+ * @param maxWidth Available wrap width in px.
526
+ * @param maxLines Cap on the returned line count.
527
+ * @returns Estimated line count, at least 1, at most `maxLines`.
421
528
  */
422
- const countWrappedLines = (text, fontSize, maxWidth, maxLines) => {
529
+ const countWrappedLines = (
530
+ text: string,
531
+ fontSize: number,
532
+ maxWidth: number,
533
+ maxLines: number,
534
+ ): number => {
423
535
  return Math.min(
424
536
  Math.max(1, splitWrappedText(text, fontSize, maxWidth).length),
425
537
  maxLines,
@@ -5,10 +5,11 @@ import { CustomError } from "./error.js";
5
5
  import { logger } from "./log.js";
6
6
 
7
7
  /**
8
- * Subset of the response payload the retryer inspects to detect
9
- * rate-limiting and credential failures.
8
+ * Error-detection fields the retryer inspects to detect rate-limiting and credential failures.
9
+ * Every fetcher's payload is intersected with
10
+ * this, so the retryer can read `errors`/`message` regardless of the payload's own shape.
10
11
  */
11
- interface ResponseData {
12
+ interface ResponseErrors {
12
13
  errors?: Array<{ type?: string; message?: string }>;
13
14
  message?: string;
14
15
  }
@@ -27,27 +28,34 @@ function getRandomInt(max: number): number {
27
28
  return Math.floor(Math.random() * max);
28
29
  }
29
30
 
30
- type FetcherResponse = AxiosResponse<ResponseData>;
31
+ /**
32
+ * A fetcher's Axios response. `TData` is the shape of `response.data`,
33
+ * which is intersected with {@link ResponseErrors} so the retryer can inspect
34
+ * `errors`/`message`.
35
+ * Defaults to `unknown` (error fields only) for callers that don't care about the payload.
36
+ */
37
+ type FetcherResponse<TData = unknown> = AxiosResponse<TData & ResponseErrors>;
31
38
 
32
- type FetcherFunction = (
39
+ type FetcherFunction<TData = unknown> = (
33
40
  variables: Record<string, unknown>,
34
41
  token: string,
35
42
  retriesForTests?: number,
36
- ) => Promise<FetcherResponse>;
43
+ ) => Promise<FetcherResponse<TData>>;
37
44
 
38
45
  /**
39
46
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
40
47
  *
48
+ * @template TData Shape of `response.data` returned by the fetcher.
41
49
  * @param fetcher The fetcher function.
42
50
  * @param variables Object with arguments to pass to the fetcher function.
43
51
  * @param pat Optional PAT override.
44
52
  * @returns The response from the fetcher function.
45
53
  */
46
- const retryer = async (
47
- fetcher: FetcherFunction,
54
+ const retryer = async <TData = unknown>(
55
+ fetcher: FetcherFunction<TData>,
48
56
  variables: Record<string, unknown>,
49
57
  pat: string | null = null,
50
- ): Promise<FetcherResponse> => {
58
+ ): Promise<FetcherResponse<TData>> => {
51
59
  const PATs = pat
52
60
  ? [{ name: "user PAT from database", value: pat }]
53
61
  : getConfig().pats;
@@ -86,7 +94,7 @@ const retryer = async (
86
94
  return response;
87
95
  }
88
96
  } catch (err) {
89
- const e = err as { response?: FetcherResponse };
97
+ const e = err as { response?: FetcherResponse<TData> };
90
98
 
91
99
  // network/unexpected error → let caller treat as failure
92
100
  if (!e.response) {
@@ -0,0 +1,136 @@
1
+ import type { AxiosResponse } from "axios";
2
+
3
+ import { MissingParamError } from "../common/error.js";
4
+ import { request } from "../common/http.js";
5
+ import { retryer } from "../common/retryer.js";
6
+
7
+ import type { GistData } from "./types.js";
8
+
9
+ const QUERY = `
10
+ query gistInfo($gistName: String!) {
11
+ viewer {
12
+ gist(name: $gistName) {
13
+ description
14
+ owner {
15
+ login
16
+ }
17
+ stargazerCount
18
+ forks {
19
+ totalCount
20
+ }
21
+ files {
22
+ name
23
+ language {
24
+ name
25
+ }
26
+ size
27
+ }
28
+ }
29
+ }
30
+ }
31
+ `;
32
+
33
+ /**
34
+ * Gist data fetcher.
35
+ *
36
+ * @param variables Fetcher variables.
37
+ * @param token GitHub token.
38
+ * @returns The response.
39
+ */
40
+ const fetcher = (
41
+ variables: Record<string, unknown>,
42
+ token: string,
43
+ ): Promise<AxiosResponse> => {
44
+ return request(
45
+ { query: QUERY, variables },
46
+ { Authorization: `token ${token}` },
47
+ );
48
+ };
49
+
50
+ /** A single file within a gist. */
51
+ interface GistFile {
52
+ name: string;
53
+ language: { name: string } | null;
54
+ size: number;
55
+ }
56
+
57
+ /** Shape of `response.data` returned by the gist GraphQL query. */
58
+ interface GistQueryResponse {
59
+ data: {
60
+ viewer: {
61
+ gist: {
62
+ description: string | null;
63
+ owner: { login: string };
64
+ stargazerCount: number;
65
+ forks: { totalCount: number };
66
+ files: Array<GistFile>;
67
+ } | null;
68
+ };
69
+ };
70
+ }
71
+
72
+ /**
73
+ * This function calculates the primary language of a gist by files size.
74
+ *
75
+ * @param files Files.
76
+ * @returns Primary language, or `null` when no file has a language.
77
+ */
78
+ const calculatePrimaryLanguage = (files: Array<GistFile>): string | null => {
79
+ const languages: Record<string, number> = {};
80
+
81
+ for (const file of files) {
82
+ if (file.language) {
83
+ languages[file.language.name] =
84
+ (languages[file.language.name] ?? 0) + file.size;
85
+ }
86
+ }
87
+
88
+ let primaryLanguage: string | null = null;
89
+ let maxSize = -1;
90
+ for (const [language, size] of Object.entries(languages)) {
91
+ if (size > maxSize) {
92
+ maxSize = size;
93
+ primaryLanguage = language;
94
+ }
95
+ }
96
+
97
+ return primaryLanguage;
98
+ };
99
+
100
+ /**
101
+ * Fetch GitHub gist information by given username and ID.
102
+ *
103
+ * @param id GitHub gist ID.
104
+ * @param pat Optional PAT override.
105
+ * @returns Gist data.
106
+ */
107
+ const fetchGist = async (
108
+ id: string,
109
+ pat: string | null = null,
110
+ ): Promise<GistData> => {
111
+ if (!id) {
112
+ throw new MissingParamError(["id"], "/api/gist?id=GIST_ID");
113
+ }
114
+ const res = await retryer<GistQueryResponse>(fetcher, { gistName: id }, pat);
115
+ if (res.data.errors) {
116
+ throw new Error(res.data.errors[0]?.message);
117
+ }
118
+ const gist = res.data.data.viewer.gist;
119
+ if (!gist) {
120
+ throw new Error("Gist not found");
121
+ }
122
+ const firstFile = gist.files[0];
123
+ if (!firstFile) {
124
+ throw new Error("Gist has no files");
125
+ }
126
+ return {
127
+ name: firstFile.name,
128
+ nameWithOwner: `${gist.owner.login}/${firstFile.name}`,
129
+ description: gist.description,
130
+ language: calculatePrimaryLanguage(gist.files),
131
+ starsCount: gist.stargazerCount,
132
+ forksCount: gist.forks.totalCount,
133
+ };
134
+ };
135
+
136
+ export { fetchGist };
@@ -51,7 +51,7 @@ const fetcher = (variables, token) => {
51
51
  );
52
52
  };
53
53
 
54
- const urlExample = "/api/pin?username=USERNAME&amp;repo=REPO_NAME";
54
+ const urlExample = "/api/pin?username=USERNAME&repo=REPO_NAME";
55
55
 
56
56
  /**
57
57
  * @typedef {import("./types").RepositoryData} RepositoryData Repository data.