@stats-organization/github-readme-stats-core 2.1.3 → 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 (123) hide show
  1. package/build/api/gist.d.ts.map +1 -1
  2. package/build/api/gist.js +34 -1
  3. package/build/api/index.d.ts.map +1 -1
  4. package/build/api/index.js +18 -1
  5. package/build/api/pin.d.ts.map +1 -1
  6. package/build/api/pin.js +17 -1
  7. package/build/api/top-langs.d.ts.map +1 -1
  8. package/build/api/top-langs.js +36 -5
  9. package/build/api/wakatime.d.ts.map +1 -1
  10. package/build/api/wakatime.js +34 -1
  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/gist.d.ts.map +1 -1
  15. package/build/cards/gist.js +0 -1
  16. package/build/cards/repo.d.ts.map +1 -1
  17. package/build/cards/repo.js +29 -21
  18. package/build/cards/stats.d.ts +4 -2
  19. package/build/cards/stats.d.ts.map +1 -1
  20. package/build/cards/stats.js +21 -9
  21. package/build/cards/top-languages.d.ts.map +1 -1
  22. package/build/cards/top-languages.js +39 -12
  23. package/build/cards/wakatime.d.ts.map +1 -1
  24. package/build/cards/wakatime.js +29 -9
  25. package/build/common/Card.d.ts +54 -60
  26. package/build/common/Card.d.ts.map +1 -1
  27. package/build/common/Card.js +88 -61
  28. package/build/common/I18n.d.ts +13 -14
  29. package/build/common/I18n.d.ts.map +1 -1
  30. package/build/common/I18n.js +13 -12
  31. package/build/common/color.d.ts +56 -32
  32. package/build/common/color.d.ts.map +1 -1
  33. package/build/common/color.js +87 -50
  34. package/build/common/config.d.ts +18 -2
  35. package/build/common/config.d.ts.map +1 -1
  36. package/build/common/config.js +17 -26
  37. package/build/common/constants.d.ts +2 -2
  38. package/build/common/constants.d.ts.map +1 -1
  39. package/build/common/constants.js +5 -3
  40. package/build/common/error.d.ts +36 -29
  41. package/build/common/error.d.ts.map +1 -1
  42. package/build/common/error.js +14 -10
  43. package/build/common/fmt.d.ts +14 -13
  44. package/build/common/fmt.d.ts.map +1 -1
  45. package/build/common/fmt.js +19 -15
  46. package/build/common/html.d.ts +2 -4
  47. package/build/common/html.d.ts.map +1 -1
  48. package/build/common/html.js +2 -6
  49. package/build/common/http.d.ts +13 -4
  50. package/build/common/http.d.ts.map +1 -1
  51. package/build/common/http.js +3 -4
  52. package/build/common/icons.d.ts +22 -21
  53. package/build/common/icons.d.ts.map +1 -1
  54. package/build/common/icons.js +4 -5
  55. package/build/common/languageColors.json +9 -1
  56. package/build/common/ops.d.ts +30 -29
  57. package/build/common/ops.d.ts.map +1 -1
  58. package/build/common/ops.js +32 -38
  59. package/build/common/render.d.ts +115 -111
  60. package/build/common/render.d.ts.map +1 -1
  61. package/build/common/render.js +138 -88
  62. package/build/common/retryer.d.ts +24 -13
  63. package/build/common/retryer.d.ts.map +1 -1
  64. package/build/common/retryer.js +22 -30
  65. package/build/fetchers/gist.d.ts +6 -21
  66. package/build/fetchers/gist.d.ts.map +1 -1
  67. package/build/fetchers/gist.js +30 -36
  68. package/build/fetchers/repo.d.ts.map +1 -1
  69. package/build/fetchers/repo.js +4 -7
  70. package/build/fetchers/stats.d.ts.map +1 -1
  71. package/build/fetchers/stats.js +3 -7
  72. package/build/fetchers/top-languages.d.ts.map +1 -1
  73. package/build/fetchers/top-languages.js +0 -1
  74. package/build/fetchers/types.d.ts +126 -0
  75. package/build/fetchers/types.d.ts.map +1 -0
  76. package/build/fetchers/types.js +1 -0
  77. package/build/fetchers/wakatime.d.ts.map +1 -1
  78. package/build/fetchers/wakatime.js +0 -1
  79. package/build/translations.d.ts +627 -24
  80. package/build/translations.d.ts.map +1 -1
  81. package/build/translations.js +7 -8
  82. package/package.json +4 -4
  83. package/src/_emoji-name-map.d.ts +10 -0
  84. package/src/api/gist.js +36 -2
  85. package/src/api/index.js +19 -2
  86. package/src/api/pin.js +18 -2
  87. package/src/api/top-langs.js +38 -6
  88. package/src/api/wakatime.js +36 -2
  89. package/src/{calculateRank.js → calculateRank.ts} +29 -19
  90. package/src/cards/gist.js +0 -2
  91. package/src/cards/repo.js +30 -22
  92. package/src/cards/stats.js +22 -10
  93. package/src/cards/top-languages.js +49 -13
  94. package/src/cards/wakatime.js +33 -10
  95. package/src/common/Card.ts +338 -0
  96. package/src/common/I18n.ts +49 -0
  97. package/src/common/color.ts +212 -0
  98. package/src/common/config.ts +83 -0
  99. package/src/common/constants.ts +10 -0
  100. package/src/common/{error.js → error.ts} +20 -14
  101. package/src/common/{fmt.js → fmt.ts} +27 -19
  102. package/src/common/{html.js → html.ts} +3 -8
  103. package/src/common/http.ts +31 -0
  104. package/src/common/{icons.js → icons.ts} +9 -7
  105. package/src/common/languageColors.json +9 -1
  106. package/src/common/{ops.js → ops.ts} +48 -52
  107. package/src/common/{render.js → render.ts} +208 -98
  108. package/src/common/retryer.ts +125 -0
  109. package/src/fetchers/gist.ts +136 -0
  110. package/src/fetchers/repo.js +4 -8
  111. package/src/fetchers/stats.js +3 -8
  112. package/src/fetchers/top-languages.js +0 -2
  113. package/src/fetchers/{types.d.ts → types.ts} +1 -1
  114. package/src/fetchers/wakatime.js +0 -2
  115. package/src/{translations.js → translations.ts} +14 -10
  116. package/src/common/Card.js +0 -275
  117. package/src/common/I18n.js +0 -42
  118. package/src/common/color.js +0 -145
  119. package/src/common/config.js +0 -78
  120. package/src/common/constants.js +0 -9
  121. package/src/common/http.js +0 -21
  122. package/src/common/retryer.js +0 -104
  123. package/src/fetchers/gist.js +0 -114
@@ -1,5 +1,4 @@
1
- // @ts-check
2
- import { getCardColors } from "./color.js";
1
+ import { getCardColors, isPrefixedHexColor } from "./color.js";
3
2
  import { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from "./error.js";
4
3
  import { encodeHTML } from "./html.js";
5
4
  import { clampValue } from "./ops.js";
@@ -7,14 +6,19 @@ import { clampValue } from "./ops.js";
7
6
  * Auto layout utility, allows us to layout things vertically or horizontally with
8
7
  * proper gaping.
9
8
  *
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.
9
+ * The caller must ensure that the passed `items` are properly sanitized!
10
+ *
11
+ * @param props Function properties.
12
+ * @param props.items Array of sanitized items to layout.
13
+ * @param props.gap Gap between items.
14
+ * @param props.direction Direction to layout items.
15
+ * @param props.sizes Array of sizes for each item.
16
+ * @returns Array of items with proper layout.
16
17
  */
17
- const flexLayout = ({ items, gap, direction, sizes = [] }) => {
18
+ const flexLayout = ({ items, gap, direction, sizes = [], }) => {
19
+ if (sizes.some((size) => !Number.isFinite(size))) {
20
+ throw new Error("flexLayout: `sizes` must contain only numbers");
21
+ }
18
22
  let lastSize = 0;
19
23
  // filter() for filtering out empty strings
20
24
  return items.filter(Boolean).map((item, i) => {
@@ -30,32 +34,53 @@ const flexLayout = ({ items, gap, direction, sizes = [] }) => {
30
34
  /**
31
35
  * Creates a node to display the primary programming language of the repository/gist.
32
36
  *
33
- * @param {string} langName Language name.
34
- * @param {string} langColor Language color.
35
- * @returns {string} Language display SVG object.
37
+ * @param langName Language name.
38
+ * @param langColor Language color.
39
+ * @returns Language display SVG object.
36
40
  */
37
41
  const createLanguageNode = (langName, langColor) => {
42
+ if (!isPrefixedHexColor(langColor)) {
43
+ throw new Error(`Invalid language color: "${langColor}"`);
44
+ }
38
45
  return `
39
46
  <g data-testid="primary-lang">
40
47
  <circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" />
41
- <text data-testid="lang-name" class="gray" x="15">${langName}</text>
48
+ <text data-testid="lang-name" class="gray" x="15">${encodeHTML(langName)}</text>
42
49
  </g>
43
50
  `;
44
51
  };
45
52
  /**
46
53
  * Create a node to indicate progress in percentage along a horizontal line.
47
54
  *
48
- * @param {Object} params Object that contains the createProgressNode parameters.
49
- * @param {number} params.x X-axis position.
50
- * @param {number} params.y Y-axis position.
51
- * @param {number} params.width Width of progress bar.
52
- * @param {string} params.color Progress color.
53
- * @param {number} params.progress Progress value.
54
- * @param {string} params.progressBarBackgroundColor Progress bar bg color.
55
- * @param {number} params.delay Delay before animation starts.
56
- * @returns {string} Progress node.
55
+ * @param params Object that contains the createProgressNode parameters.
56
+ * @param params.x X-axis position.
57
+ * @param params.y Y-axis position.
58
+ * @param params.width Width of progress bar.
59
+ * @param params.color Progress color.
60
+ * @param params.progress Progress value.
61
+ * @param params.progressBarBackgroundColor Progress bar bg color.
62
+ * @param params.delay Delay before animation starts.
63
+ * @returns Progress node.
57
64
  */
58
65
  const createProgressNode = ({ x, y, width, color, progress, progressBarBackgroundColor, delay, }) => {
66
+ if (!isPrefixedHexColor(color)) {
67
+ throw new Error(`Invalid progress color: "${color}"`);
68
+ }
69
+ if (!isPrefixedHexColor(progressBarBackgroundColor)) {
70
+ throw new Error(`Invalid progress bar background color: "${progressBarBackgroundColor}"`);
71
+ }
72
+ if (!Number.isFinite(width)) {
73
+ throw new Error(`Invalid width: "${width}"`);
74
+ }
75
+ if (!Number.isFinite(x)) {
76
+ throw new Error(`Invalid x: "${x}"`);
77
+ }
78
+ if (!Number.isFinite(y)) {
79
+ throw new Error(`Invalid y: "${y}"`);
80
+ }
81
+ if (!Number.isFinite(delay)) {
82
+ throw new Error(`Invalid delay: "${delay}"`);
83
+ }
59
84
  const progressPercentage = clampValue(progress, 2, 100);
60
85
  return `
61
86
  <svg width="${width}" x="${x}" y="${y}">
@@ -77,22 +102,37 @@ const createProgressNode = ({ x, y, width, color, progress, progressBarBackgroun
77
102
  * native, font-aware wrapping. Content overflowing `lineCount` lines is
78
103
  * clipped (with an ellipsis on the last visible line) by CSS line-clamp.
79
104
  *
80
- * @param {object} props Function properties.
81
- * @param {string} props.text Text to render (will be HTML-encoded).
82
- * @param {number} props.x X position of the foreignObject.
83
- * @param {number} props.y Y position of the foreignObject.
84
- * @param {number} props.width Width of the wrap box.
85
- * @param {number} props.height Height of the wrap box.
86
- * @param {number} props.lineCount Maximum number of lines to display.
87
- * @param {string} props.className CSS class applied to the inner element.
88
- * @param {string=} props.testId Optional test id for the inner element.
89
- * @returns {string} foreignObject SVG node.
105
+ * @param props Function properties.
106
+ * @param props.text Text to render (will be HTML-encoded).
107
+ * @param props.x X position of the foreignObject.
108
+ * @param props.y Y position of the foreignObject.
109
+ * @param props.width Width of the wrap box.
110
+ * @param props.height Height of the wrap box.
111
+ * @param props.lineCount Maximum number of lines to display.
112
+ * @param props.className CSS class applied to the inner element.
113
+ * @param props.testId Optional test id for the inner element.
114
+ * @returns foreignObject SVG node.
90
115
  */
91
116
  const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, testId, }) => {
92
- const testIdAttr = testId ? ` data-testid="${testId}"` : "";
117
+ if (!Number.isFinite(x)) {
118
+ throw new Error(`Invalid x: "${x}"`);
119
+ }
120
+ if (!Number.isFinite(y)) {
121
+ throw new Error(`Invalid y: "${y}"`);
122
+ }
123
+ if (!Number.isFinite(width)) {
124
+ throw new Error(`Invalid width: "${width}"`);
125
+ }
126
+ if (!Number.isFinite(height)) {
127
+ throw new Error(`Invalid height: "${height}"`);
128
+ }
129
+ if (!Number.isFinite(lineCount)) {
130
+ throw new Error(`Invalid lineCount: "${lineCount}"`);
131
+ }
132
+ const testIdAttr = testId ? ` data-testid="${encodeHTML(testId)}"` : "";
93
133
  return `
94
134
  <foreignObject x="${x}" y="${y}" width="${width}" height="${height}">
95
- <div xmlns="http://www.w3.org/1999/xhtml" class="${className}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(text)}</div>
135
+ <div xmlns="http://www.w3.org/1999/xhtml" class="${encodeHTML(className)}" style="--lines: ${lineCount};"${testIdAttr}>${encodeHTML(text)}</div>
96
136
  </foreignObject>
97
137
  `;
98
138
  };
@@ -102,36 +142,46 @@ const wrappedTextNode = ({ text, x, y, width, height, lineCount, className, test
102
142
  * browser handles wrapping and the line count is taken from the `--lines`
103
143
  * custom property set on the element.
104
144
  *
105
- * @param {string} color Text color (CSS `color` property).
106
- * @returns {string} CSS rules block (without the surrounding selector).
145
+ * @param color Text color (CSS `color` property).
146
+ * @returns CSS rules block (without the surrounding selector).
107
147
  */
108
- const wrappedTextStyles = (color) => `
109
- color: ${color};
110
- margin: 0;
111
- line-height: 1.2;
112
- overflow-wrap: anywhere;
113
- word-break: break-word;
114
- display: -webkit-box;
115
- -webkit-box-orient: vertical;
116
- -webkit-line-clamp: var(--lines);
117
- line-clamp: var(--lines);
118
- overflow: hidden;
119
- text-overflow: ellipsis;
120
- padding-bottom: 0.15em;
121
- `;
148
+ const wrappedTextStyles = (color) => {
149
+ if (!isPrefixedHexColor(color)) {
150
+ throw new Error(`Invalid text color: "${color}"`);
151
+ }
152
+ return `
153
+ color: ${color};
154
+ margin: 0;
155
+ line-height: 1.2;
156
+ overflow-wrap: anywhere;
157
+ word-break: break-word;
158
+ display: -webkit-box;
159
+ -webkit-box-orient: vertical;
160
+ -webkit-line-clamp: var(--lines);
161
+ line-clamp: var(--lines);
162
+ overflow: hidden;
163
+ text-overflow: ellipsis;
164
+ padding-bottom: 0.15em;
165
+ `;
166
+ };
122
167
  /**
123
168
  * Creates an icon with label to display repository/gist stats like forks, stars, etc.
124
169
  *
125
- * @param {string} icon The icon to display.
126
- * @param {number|string} label The label to display.
127
- * @param {string} testid The testid to assign to the label.
128
- * @param {number} iconSize The size of the icon.
129
- * @returns {string} Icon with label SVG object.
170
+ * The caller must ensure that the passed `icon` is properly sanitized!
171
+ *
172
+ * @param icon The sanitized icon to display.
173
+ * @param label The label to display.
174
+ * @param testid The testid to assign to the label.
175
+ * @param iconSize The size of the icon.
176
+ * @returns Icon with label SVG object.
130
177
  */
131
178
  const iconWithLabel = (icon, label, testid, iconSize) => {
132
179
  if (typeof label === "number" && label <= 0) {
133
180
  return "";
134
181
  }
182
+ if (!Number.isFinite(iconSize)) {
183
+ throw new Error(`Invalid iconSize: "${iconSize}"`);
184
+ }
135
185
  const iconSvg = `
136
186
  <svg
137
187
  class="icon"
@@ -144,7 +194,7 @@ const iconWithLabel = (icon, label, testid, iconSize) => {
144
194
  ${icon}
145
195
  </svg>
146
196
  `;
147
- const text = `<text data-testid="${testid}" class="gray">${label}</text>`;
197
+ const text = `<text data-testid="${encodeHTML(testid)}" class="gray">${encodeHTML(String(label))}</text>`;
148
198
  return flexLayout({ items: [iconSvg, text], gap: 20 }).join("");
149
199
  };
150
200
  // Script parameters.
@@ -156,17 +206,17 @@ const UPSTREAM_API_ERRORS = [
156
206
  /**
157
207
  * Renders error message on the card.
158
208
  *
159
- * @param {object} args Function arguments.
160
- * @param {string} args.message Main error message.
161
- * @param {string} [args.secondaryMessage=""] The secondary error message.
162
- * @param {object} [args.renderOptions={}] Render options.
163
- * @param {string=} args.renderOptions.title_color Card title color.
164
- * @param {string=} args.renderOptions.text_color Card text color.
165
- * @param {string=} args.renderOptions.bg_color Card background color.
166
- * @param {string=} args.renderOptions.border_color Card border color.
167
- * @param {Parameters<typeof getCardColors>[0]["theme"]=} args.renderOptions.theme Card theme.
168
- * @param {boolean=} args.renderOptions.show_repo_link Whether to show repo link or not.
169
- * @returns {string} The SVG markup.
209
+ * @param args Function arguments.
210
+ * @param args.message Main error message.
211
+ * @param args.secondaryMessage The secondary error message.
212
+ * @param args.renderOptions Render options.
213
+ * @param args.renderOptions.title_color Card title color.
214
+ * @param args.renderOptions.text_color Card text color.
215
+ * @param args.renderOptions.bg_color Card background color.
216
+ * @param args.renderOptions.border_color Card border color.
217
+ * @param args.renderOptions.theme Card theme.
218
+ * @param args.renderOptions.show_repo_link Whether to show repo link or not.
219
+ * @returns The SVG markup.
170
220
  */
171
221
  const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) => {
172
222
  const { title_color, text_color, bg_color, border_color, theme = "default", show_repo_link = true, } = renderOptions;
@@ -181,19 +231,19 @@ const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) =>
181
231
  theme,
182
232
  });
183
233
  return `
184
- <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${bgColor}" xmlns="http://www.w3.org/2000/svg">
234
+ <svg width="${ERROR_CARD_LENGTH}" height="120" viewBox="0 0 ${ERROR_CARD_LENGTH} 120" fill="${String(bgColor)}" xmlns="http://www.w3.org/2000/svg">
185
235
  <style>
186
236
  .text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor} }
187
237
  .small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
188
238
  .gray { fill: #858585 }
189
239
  </style>
190
- <rect x="0.5" y="0.5" width="${ERROR_CARD_LENGTH - 1}" height="99%" rx="4.5" fill="${bgColor}" stroke="${borderColor}"/>
240
+ <rect x="0.5" y="0.5" width="${ERROR_CARD_LENGTH - 1}" height="99%" rx="4.5" fill="${String(bgColor)}" stroke="${borderColor}"/>
191
241
  <text x="25" y="45" class="text">Something went wrong!${UPSTREAM_API_ERRORS.includes(secondaryMessage) || !show_repo_link
192
242
  ? ""
193
243
  : " file an issue at https://tinyurl.com/github-stats"}</text>
194
244
  <text data-testid="message" x="25" y="55" class="text small">
195
245
  <tspan x="25" dy="18">${encodeHTML(message)}</tspan>
196
- <tspan x="25" dy="18" class="gray">${secondaryMessage}</tspan>
246
+ <tspan x="25" dy="18" class="gray">${encodeHTML(secondaryMessage)}</tspan>
197
247
  </text>
198
248
  </svg>
199
249
  `;
@@ -202,9 +252,9 @@ const renderError = ({ message, secondaryMessage = "", renderOptions = {}, }) =>
202
252
  * Retrieve text length based on Segoe UI font.
203
253
  *
204
254
  * @see https://stackoverflow.com/a/48172630/10629172
205
- * @param {string} str String to measure.
206
- * @param {number} fontSize Font size.
207
- * @returns {number} Text length.
255
+ * @param str String to measure.
256
+ * @param fontSize Font size.
257
+ * @returns Text length.
208
258
  */
209
259
  const measureText = (str, fontSize = 10) => {
210
260
  // prettier-ignore
@@ -255,7 +305,7 @@ const measureText = (str, fontSize = 10) => {
255
305
  return 1;
256
306
  }
257
307
  if (c.charCodeAt(0) < widths.length) {
258
- return widths[c.charCodeAt(0)];
308
+ return widths[c.charCodeAt(0)] ?? avg;
259
309
  }
260
310
  else {
261
311
  return avg;
@@ -270,10 +320,10 @@ const measureText = (str, fontSize = 10) => {
270
320
  * The browser still does the real wrap inside the foreignObject; this is only
271
321
  * used to size the SVG.
272
322
  *
273
- * @param {string} text Text to split.
274
- * @param {number} fontSize Font size in px (matches `measureText`).
275
- * @param {number} maxWidth Available wrap width in px.
276
- * @returns {string[]} Estimated wrapped lines.
323
+ * @param text Text to split.
324
+ * @param fontSize Font size in px (matches `measureText`).
325
+ * @param maxWidth Available wrap width in px.
326
+ * @returns Estimated wrapped lines.
277
327
  */
278
328
  const splitWrappedText = (text, fontSize, maxWidth) => {
279
329
  if (!text) {
@@ -289,8 +339,8 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
289
339
  // Korean Hangul (U+AC00–U+D7AF) is intentionally NOT in the CJK range
290
340
  // because Korean wraps at word boundaries by default in HTML.
291
341
  // ASCII whitespace is collapsed to a single space per CSS `white-space: normal;`
292
- text = text.replace(/[\t\n\r ]+/g, " ");
293
- const tokens = text.match(/\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g);
342
+ const normalizedText = text.replace(/[\t\n\r ]+/g, " ");
343
+ const tokens = normalizedText.match(/\s|[\u3000-\u9FFF\uFF00-\uFFEF]|[^\s\u3000-\u9FFF\uFF00-\uFFEF]+/g);
294
344
  if (!tokens) {
295
345
  return [];
296
346
  }
@@ -319,7 +369,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
319
369
  if (currentWidth === 0) {
320
370
  continue;
321
371
  }
322
- lines[lines.length - 1] += token;
372
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + token;
323
373
  currentWidth += measureText(token, fontSize);
324
374
  continue;
325
375
  }
@@ -327,7 +377,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
327
377
  while (remaining) {
328
378
  const w = measureText(remaining, fontSize);
329
379
  if (currentWidth + w <= maxWidth) {
330
- lines[lines.length - 1] += remaining;
380
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + remaining;
331
381
  currentWidth += w;
332
382
  break;
333
383
  }
@@ -338,7 +388,7 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
338
388
  }
339
389
  // An atom wider than the box wraps mid-glyph (overflow-wrap: anywhere).
340
390
  const { segment, width } = takeFittingSegment(remaining, maxWidth);
341
- lines[lines.length - 1] += segment;
391
+ lines[lines.length - 1] = (lines[lines.length - 1] ?? "") + segment;
342
392
  currentWidth = width;
343
393
  remaining = remaining.slice(segment.length);
344
394
  }
@@ -349,11 +399,11 @@ const splitWrappedText = (text, fontSize, maxWidth) => {
349
399
  * Estimate how many lines a string will wrap to when laid out greedily at the
350
400
  * given font size inside a box of width `maxWidth`, capped at `maxLines`.
351
401
  *
352
- * @param {string} text Text to estimate.
353
- * @param {number} fontSize Font size in px (matches `measureText`).
354
- * @param {number} maxWidth Available wrap width in px.
355
- * @param {number} maxLines Cap on the returned line count.
356
- * @returns {number} Estimated line count, at least 1, at most `maxLines`.
402
+ * @param text Text to estimate.
403
+ * @param fontSize Font size in px (matches `measureText`).
404
+ * @param maxWidth Available wrap width in px.
405
+ * @param maxLines Cap on the returned line count.
406
+ * @returns Estimated line count, at least 1, at most `maxLines`.
357
407
  */
358
408
  const countWrappedLines = (text, fontSize, maxWidth, maxLines) => {
359
409
  return Math.min(Math.max(1, splitWrappedText(text, fontSize, maxWidth).length), maxLines);
@@ -1,22 +1,33 @@
1
+ import type { AxiosResponse } from "axios";
1
2
  /**
2
- * Axios response.
3
+ * Error-detection fields the retryer inspects to detect rate-limiting and credential failures.
4
+ * Every fetcher's payload is intersected with
5
+ * this, so the retryer can read `errors`/`message` regardless of the payload's own shape.
3
6
  */
4
- export type AxiosResponse = import("axios").AxiosResponse;
7
+ interface ResponseErrors {
8
+ errors?: Array<{
9
+ type?: string;
10
+ message?: string;
11
+ }>;
12
+ message?: string;
13
+ }
5
14
  /**
6
- * Fetcher function.
7
- */
8
- export type FetcherFunction = (variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>;
9
- /**
10
- * @typedef {import("axios").AxiosResponse} AxiosResponse Axios response.
11
- * @typedef {(variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>} FetcherFunction Fetcher function.
15
+ * A fetcher's Axios response. `TData` is the shape of `response.data`,
16
+ * which is intersected with {@link ResponseErrors} so the retryer can inspect
17
+ * `errors`/`message`.
18
+ * Defaults to `unknown` (error fields only) for callers that don't care about the payload.
12
19
  */
20
+ type FetcherResponse<TData = unknown> = AxiosResponse<TData & ResponseErrors>;
21
+ type FetcherFunction<TData = unknown> = (variables: Record<string, unknown>, token: string, retriesForTests?: number) => Promise<FetcherResponse<TData>>;
13
22
  /**
14
23
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
15
24
  *
16
- * @param {FetcherFunction} fetcher The fetcher function.
17
- * @param {any} variables Object with arguments to pass to the fetcher function.
18
- * @param {string | null} pat Optional PAT override.
19
- * @returns {Promise<any>} The response from the fetcher function.
25
+ * @template TData Shape of `response.data` returned by the fetcher.
26
+ * @param fetcher The fetcher function.
27
+ * @param variables Object with arguments to pass to the fetcher function.
28
+ * @param pat Optional PAT override.
29
+ * @returns The response from the fetcher function.
20
30
  */
21
- export function retryer(fetcher: FetcherFunction, variables: any, pat?: string | null): Promise<any>;
31
+ declare const retryer: <TData = unknown>(fetcher: FetcherFunction<TData>, variables: Record<string, unknown>, pat?: string | null) => Promise<FetcherResponse<TData>>;
32
+ export { retryer };
22
33
  //# sourceMappingURL=retryer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.js"],"names":[],"mappings":";;;4BAqBa,OAAO,OAAO,EAAE,aAAa;;;;8BAC7B,CAAC,SAAS,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,aAAa,CAAC;AAFhG;;;GAGG;AAEH;;;;;;;GAOG;AACH,iCALW,eAAe,aACf,GAAG,QACH,MAAM,GAAG,IAAI,GACX,OAAO,CAAC,GAAG,CAAC,CAsExB"}
1
+ {"version":3,"file":"retryer.d.ts","sourceRoot":"","sources":["../../src/common/retryer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAM3C;;;;GAIG;AACH,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAgBD;;;;;GAKG;AACH,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,IAAI,aAAa,CAAC,KAAK,GAAG,cAAc,CAAC,CAAC;AAE9E,KAAK,eAAe,CAAC,KAAK,GAAG,OAAO,IAAI,CACtC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,KAAK,EAAE,MAAM,EACb,eAAe,CAAC,EAAE,MAAM,KACrB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;AAErC;;;;;;;;GAQG;AACH,QAAA,MAAM,OAAO,GAAU,KAAK,GAAG,OAAO,EACpC,SAAS,eAAe,CAAC,KAAK,CAAC,EAC/B,WAAW,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,MAAK,MAAM,GAAG,IAAW,KACxB,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAiEhC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC"}
@@ -1,4 +1,3 @@
1
- // @ts-check
2
1
  import { getConfig } from "./config.js";
3
2
  import { CustomError } from "./error.js";
4
3
  import { logger } from "./log.js";
@@ -8,51 +7,45 @@ import { logger } from "./log.js";
8
7
  * The value is generated using `Math.random()` and uniformly distributed
9
8
  * across the range.
10
9
  *
11
- * @param {number} max The upper bound (exclusive). Must be a positive number.
10
+ * @param max The upper bound (exclusive). Must be a positive number.
12
11
  *
13
- * @returns {number} A random integer `n` such that `0 <= n < max`.
12
+ * @returns A random integer `n` such that `0 <= n < max`.
14
13
  */
15
14
  function getRandomInt(max) {
16
15
  return Math.floor(Math.random() * max);
17
16
  }
18
- /**
19
- * @typedef {import("axios").AxiosResponse} AxiosResponse Axios response.
20
- * @typedef {(variables: any, token: string, retriesForTests?: number) => Promise<AxiosResponse>} FetcherFunction Fetcher function.
21
- */
22
17
  /**
23
18
  * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
24
19
  *
25
- * @param {FetcherFunction} fetcher The fetcher function.
26
- * @param {any} variables Object with arguments to pass to the fetcher function.
27
- * @param {string | null} pat Optional PAT override.
28
- * @returns {Promise<any>} The response from the fetcher function.
20
+ * @template TData Shape of `response.data` returned by the fetcher.
21
+ * @param fetcher The fetcher function.
22
+ * @param variables Object with arguments to pass to the fetcher function.
23
+ * @param pat Optional PAT override.
24
+ * @returns The response from the fetcher function.
29
25
  */
30
26
  const retryer = async (fetcher, variables, pat = null) => {
31
- let PATs;
32
- if (pat) {
33
- PATs = [{ name: "user PAT from database", value: pat }];
34
- }
35
- else {
36
- PATs = getConfig().pats;
37
- }
27
+ const PATs = pat
28
+ ? [{ name: "user PAT from database", value: pat }]
29
+ : getConfig().pats;
38
30
  if (!PATs.length) {
39
31
  throw new CustomError("No GitHub API tokens found", CustomError.NO_TOKENS);
40
32
  }
41
33
  const startPAT = getRandomInt(PATs.length);
42
34
  for (let retries = 0; retries < PATs.length; retries++) {
43
35
  const currentPAT = PATs[(startPAT + retries) % PATs.length];
36
+ if (!currentPAT) {
37
+ continue;
38
+ }
44
39
  try {
45
- let response = await fetcher(variables,
46
- // @ts-ignore
47
- currentPAT.value,
40
+ const response = await fetcher(variables, currentPAT.value,
48
41
  // used in tests for faking rate limit
49
42
  retries);
50
43
  // react on both type and message-based rate-limit signals.
51
44
  // https://github.com/anuraghazra/github-readme-stats/issues/4425
52
- const errors = response?.data?.errors;
45
+ const errors = response.data.errors;
53
46
  const errorType = errors?.[0]?.type;
54
- const errorMsg = errors?.[0]?.message || "";
55
- const isRateLimited = (errors && errorType === "RATE_LIMITED") ||
47
+ const errorMsg = errors?.[0]?.message ?? "";
48
+ const isRateLimited = (!!errors && errorType === "RATE_LIMITED") ||
56
49
  /rate limit/i.test(errorMsg);
57
50
  if (isRateLimited) {
58
51
  logger.log(`${currentPAT.name} Failed due to rate limiting`);
@@ -62,16 +55,15 @@ const retryer = async (fetcher, variables, pat = null) => {
62
55
  }
63
56
  }
64
57
  catch (err) {
65
- /** @type {any} */
66
58
  const e = err;
67
59
  // network/unexpected error → let caller treat as failure
68
- if (!e?.response) {
69
- throw e;
60
+ if (!e.response) {
61
+ throw err;
70
62
  }
71
- // prettier-ignore
72
63
  // also checking for bad credentials if any tokens gets invalidated
73
- const isBadCredential = e?.response?.data?.message === "Bad credentials";
74
- const isAccountSuspended = e?.response?.data?.message === "Sorry. Your account was suspended.";
64
+ const message = e.response.data.message;
65
+ const isBadCredential = message === "Bad credentials";
66
+ const isAccountSuspended = message === "Sorry. Your account was suspended.";
75
67
  if (isBadCredential || isAccountSuspended) {
76
68
  logger.log(`${currentPAT.name} Failed due to bad credentials`);
77
69
  }
@@ -1,26 +1,11 @@
1
- /**
2
- * Gist file.
3
- */
4
- export type GistFile = {
5
- name: string;
6
- language: {
7
- name: string;
8
- };
9
- size: number;
10
- };
11
- /**
12
- * Gist data.
13
- */
14
- export type GistData = any;
15
- /**
16
- * @typedef {import('./types').GistData} GistData Gist data.
17
- */
1
+ import type { GistData } from "./types.js";
18
2
  /**
19
3
  * Fetch GitHub gist information by given username and ID.
20
4
  *
21
- * @param {string} id GitHub gist ID.
22
- * @param {string | null} pat Optional PAT override.
23
- * @returns {Promise<GistData>} Gist data.
5
+ * @param id GitHub gist ID.
6
+ * @param pat Optional PAT override.
7
+ * @returns Gist data.
24
8
  */
25
- export function fetchGist(id: string, pat?: string | null): Promise<GistData>;
9
+ declare const fetchGist: (id: string, pat?: string | null) => Promise<GistData>;
10
+ export { fetchGist };
26
11
  //# sourceMappingURL=gist.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"gist.d.ts","sourceRoot":"","sources":["../../src/fetchers/gist.js"],"names":[],"mappings":";;;uBA6Ca;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;KAAE,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE;;;;;AAiCxE;;GAEG;AAEH;;;;;;GAMG;AACH,8BAJW,MAAM,QACN,MAAM,GAAG,IAAI,GACX,OAAO,CAAC,QAAQ,CAAC,CAwB7B"}
1
+ {"version":3,"file":"gist.d.ts","sourceRoot":"","sources":["../../src/fetchers/gist.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA6F3C;;;;;;GAMG;AACH,QAAA,MAAM,SAAS,GACb,IAAI,MAAM,EACV,MAAK,MAAM,GAAG,IAAW,KACxB,OAAO,CAAC,QAAQ,CAwBlB,CAAC;AAEF,OAAO,EAAE,SAAS,EAAE,CAAC"}