@kudoai/chatgpt.js 3.0.3 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,8 +45,8 @@
45
45
  [![](https://img.shields.io/github/stars/KudoAI/chatgpt.js?label=Stars&color=af68ff&logo=github&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/stargazers)
46
46
  [![](https://img.shields.io/badge/License-MIT-green.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/blob/main/LICENSE.md)
47
47
  [![](https://img.shields.io/github/commit-activity/m/KudoAI/chatgpt.js?label=Commits&logo=github&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/commits/main)
48
- ![](https://img.shields.io/badge/Clones-326/month-869da0?logo=github&logoColor=white&labelColor=464646&style=for-the-badge)
49
- [![](https://img.shields.io/github/size/KudoAI/chatgpt.js/dist/chatgpt.min.js?branch=v3.0.3&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/tree/v3.0.3/dist/chatgpt.min.js)
48
+ ![](https://img.shields.io/badge/Clones-390/month-869da0?logo=github&logoColor=white&labelColor=464646&style=for-the-badge)
49
+ [![](https://img.shields.io/github/size/KudoAI/chatgpt.js/dist/chatgpt.min.js?branch=v3.1.0&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/tree/v3.1.0/dist/chatgpt.min.js)
50
50
  [![](https://img.shields.io/codefactor/grade/github/kudoai/chatgpt.js?label=Code+Quality&logo=codefactor&logoColor=white&labelColor=464646&color=1acc6c&style=for-the-badge)](https://www.codefactor.io/repository/github/kudoai/chatgpt.js)
51
51
  [![](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dkudoai_chatgpt.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold)](https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=kudoai_chatgpt.js)
52
52
  [![](https://img.shields.io/badge/Mentioned_in-Awesome-cca8c4?logo=awesomelists&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/sindresorhus/awesome-chatgpt#javascript)
@@ -84,7 +84,7 @@
84
84
 
85
85
  ```js
86
86
  (async () => {
87
- await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js');
87
+ await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js');
88
88
  // Your code here...
89
89
  })();
90
90
  ```
@@ -93,7 +93,7 @@
93
93
 
94
94
  ```js
95
95
  var xhr = new XMLHttpRequest();
96
- xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js');
96
+ xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js');
97
97
  xhr.onload = function () {
98
98
  if (xhr.status === 200) {
99
99
  var chatgptJS = document.createElement('script');
@@ -115,7 +115,7 @@ function yourCode() {
115
115
 
116
116
  ```js
117
117
  ...
118
- // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js
118
+ // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js
119
119
  // ==/UserScript==
120
120
 
121
121
  // Your code here...
@@ -190,7 +190,7 @@ chatgpt.get('reply', 'last');
190
190
 
191
191
  Each call equally fetches the last response. If you think it works, it probably will... so just type it!
192
192
 
193
- If it didn't, check out the extended [userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.0.3/docs/USERGUIDE.md), or simply submit an [issue](https://github.com/KudoAI/chatgpt.js/issues) or [PR](https://github.com/KudoAI/chatgpt.js/pulls) and it will be integrated, ezpz!
193
+ If it didn't, check out the extended [userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.1.0/docs/USERGUIDE.md), or simply submit an [issue](https://github.com/KudoAI/chatgpt.js/issues) or [PR](https://github.com/KudoAI/chatgpt.js/pulls) and it will be integrated, ezpz!
194
194
 
195
195
  <img height=8px width="100%" src="https://media.chatgptjs.org/images/separators/gradient-aqua.png?78210a7">
196
196
 
@@ -360,7 +360,7 @@ This library exists thanks to code, translations, issues & ideas from the follow
360
360
  <div align="center">
361
361
 
362
362
  **[Releases](https://github.com/KudoAI/chatgpt.js/releases)** /
363
- [Userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.0.3/docs/USERGUIDE.md) /
363
+ [Userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.1.0/docs/USERGUIDE.md) /
364
364
  [Discuss](https://github.com/KudoAI/chatgpt.js/discussions) /
365
365
  <a href="#--------------------------------------------------------------------------------english---------简体中文---------繁體中文---------日本---------한국인---------हिंदी---------नेपाली---------deutsch---------español---------français---------italiano---------nederlands---------português---------việt----">Back to top ↑</a>
366
366
 
package/chatgpt.js CHANGED
@@ -85,9 +85,10 @@ const chatgpt = { // eslint-disable-line no-redeclare
85
85
  document.head.append(modalStyle);
86
86
  }
87
87
  modalStyle.innerText = ( // update prev/new style contents
88
+ '.no-mobile-tap-outline { outline: none ; -webkit-tap-highlight-color: transparent }'
88
89
 
89
90
  // Background styles
90
- '.chatgpt-modal {'
91
+ + '.chatgpt-modal {'
91
92
  + 'position: fixed ; top: 0 ; left: 0 ; width: 100% ; height: 100% ;' // expand to full view-port
92
93
  + 'background-color: rgba(67, 70, 72, 0) ;' // init dim bg but no opacity
93
94
  + 'transition: background-color 0.05s ease ;' // speed to transition in show alert routine
@@ -148,7 +149,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
148
149
 
149
150
  // Create/append buttons (if provided) to buttons div
150
151
  const modalButtons = document.createElement('div');
151
- modalButtons.classList.add('modal-buttons');
152
+ modalButtons.classList.add('modal-buttons', 'no-mobile-tap-outline');
152
153
  if (btns) { // are supplied
153
154
  if (!Array.isArray(btns)) btns = [btns]; // convert single button to array if necessary
154
155
  btns.forEach((buttonFn) => { // create title-cased labels + attach listeners
@@ -157,7 +158,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
157
158
  .replace(/[_-]\w/g, match => match.slice(1).toUpperCase()) // convert snake/kebab to camel case
158
159
  .replace(/([A-Z])/g, ' $1') // insert spaces
159
160
  .replace(/^\w/, firstChar => firstChar.toUpperCase()); // capitalize first letter
160
- button.addEventListener('click', () => { dismissAlert(); buttonFn(); });
161
+ button.onclick = () => { dismissAlert(); buttonFn(); };
161
162
  modalButtons.insertBefore(button, modalButtons.firstChild); // insert button to left
162
163
  });
163
164
  }
@@ -177,12 +178,11 @@ const chatgpt = { // eslint-disable-line no-redeclare
177
178
  const checkboxFn = checkbox, // assign the named function to checkboxFn
178
179
  checkboxInput = document.createElement('input');
179
180
  checkboxInput.type = 'checkbox';
180
- checkboxInput.addEventListener('change', checkboxFn);
181
+ checkboxInput.onchange = checkboxFn;
181
182
 
182
183
  // Create/show label
183
184
  const checkboxLabel = document.createElement('label');
184
- checkboxLabel.addEventListener('click', () => {
185
- checkboxInput.checked = !checkboxInput.checked; checkboxFn(); });
185
+ checkboxLabel.onclick = () => { checkboxInput.checked = !checkboxInput.checked; checkboxFn(); };
186
186
  checkboxLabel.textContent = checkboxFn.name.charAt(0).toUpperCase() // capitalize first char
187
187
  + checkboxFn.name.slice(1) // format remaining chars
188
188
  .replace(/([A-Z])/g, (match, letter) => ' ' + letter.toLowerCase()) // insert spaces, convert to lowercase
@@ -194,7 +194,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
194
194
 
195
195
  // Create close button
196
196
  const closeBtn = document.createElement('div');
197
- closeBtn.title = 'Close'; closeBtn.classList.add('modal-close-btn');
197
+ closeBtn.title = 'Close'; closeBtn.classList.add('modal-close-btn', 'no-mobile-tap-outline');
198
198
  const closeSVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
199
199
  closeSVG.setAttribute('height', '10px');
200
200
  closeSVG.setAttribute('viewBox', '0 0 14 14');
@@ -247,8 +247,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
247
247
 
248
248
  // Add listeners to dismiss alert
249
249
  const dismissElems = [modalContainer, closeBtn, closeSVG, dismissBtn];
250
- dismissElems.forEach(elem => {
251
- elem.addEventListener('click', clickHandler); });
250
+ dismissElems.forEach(elem => elem.onclick = clickHandler);
252
251
  document.addEventListener('keydown', keyHandler);
253
252
 
254
253
  // Define alert dismisser
@@ -262,10 +261,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
262
261
  alertQueue = JSON.parse(localStorage.alertQueue);
263
262
  alertQueue.shift(); // + memory
264
263
  localStorage.alertQueue = JSON.stringify(alertQueue); // + storage
265
-
266
- // Remove all listeners to prevent memory leaks
267
- dismissElems.forEach(elem => { elem.removeEventListener('click', clickHandler); });
268
- document.removeEventListener('keydown', keyHandler);
264
+ document.removeEventListener('keydown', keyHandler); // prevent memory leaks
269
265
 
270
266
  // Check for pending alerts in queue
271
267
  if (alertQueue.length > 0) {
@@ -300,8 +296,10 @@ const chatgpt = { // eslint-disable-line no-redeclare
300
296
  const randomDelay = Math.max(2, Math.floor(chatgpt.randomFloat() * 21 - 10)); // set random delay up to ±10 secs
301
297
  autoRefresh.isActive = setTimeout(() => {
302
298
  const manifestScript = document.querySelector('script[src*="_ssgManifest.js"]');
303
- document.querySelector('#refresh-frame').src = manifestScript.src + '?' + Date.now();
304
- console.log('↻ ChatGPT >> [' + autoRefresh.nowTimeStamp() + '] ChatGPT session refreshed');
299
+ if (manifestScript) {
300
+ document.querySelector('#refresh-frame').src = manifestScript.src + '?' + Date.now();
301
+ console.log('↻ ChatGPT >> [' + autoRefresh.nowTimeStamp() + '] ChatGPT session refreshed');
302
+ }
305
303
  scheduleRefreshes(interval);
306
304
  }, (interval + randomDelay) * 1000);
307
305
  };
@@ -309,8 +307,8 @@ const chatgpt = { // eslint-disable-line no-redeclare
309
307
  console.log('↻ ChatGPT >> [' + chatgpt.autoRefresh.nowTimeStamp() + '] Auto refresh activated');
310
308
 
311
309
  // Add listener to send beacons in Chromium to thwart auto-discards if Page Visibility API supported
312
- if (navigator.userAgent.includes('Chrome') && typeof document.hidden !== 'undefined') {
313
- document.addEventListener('visibilitychange', this.toggle.beacons); }
310
+ if (navigator.userAgent.includes('Chrome') && typeof document.hidden !== 'undefined')
311
+ document.addEventListener('visibilitychange', this.toggle.beacons);
314
312
  },
315
313
 
316
314
  deactivate() {
@@ -421,20 +419,20 @@ const chatgpt = { // eslint-disable-line no-redeclare
421
419
  await new Promise(resolve => { // when reply starts generating
422
420
  (function checkReplyExists() {
423
421
  const msgDivs = document.querySelectorAll('div[data-message-author-role]');
424
- msgDivs[msgDivs.length - 1].dataset.messageAuthorRole == 'assistant' ? resolve(true)
422
+ msgDivs[msgDivs.length - 1]?.dataset.messageAuthorRole == 'assistant' ? resolve(true)
425
423
  : setTimeout(checkReplyExists, 200); })();
426
424
  });
427
425
  const lastReplyDiv = await new Promise(resolve => { // when code starts generating
428
426
  (function checkPreExists() {
429
427
  const replyDivs = document.querySelectorAll('div[data-message-author-role="assistant"]'),
430
428
  lastReplyDiv = replyDivs[replyDivs.length - 1];
431
- lastReplyDiv.querySelector('pre') ? resolve(lastReplyDiv)
429
+ lastReplyDiv?.querySelector('pre') ? resolve(lastReplyDiv)
432
430
  : setTimeout(checkPreExists, 200); })();
433
431
  });
434
432
  return Promise.race([
435
433
  new Promise(resolve => { // when code block not last child of reply div
436
434
  (function checkPreNotLast() {
437
- lastReplyDiv.querySelector('pre').nextElementSibling ? resolve(true)
435
+ lastReplyDiv?.querySelector('pre').nextElementSibling ? resolve(true)
438
436
  : setTimeout(checkPreNotLast, 200); })();
439
437
  }), chatgpt.isIdle() // ...or reply stopped generating
440
438
  ]);
@@ -544,9 +542,9 @@ const chatgpt = { // eslint-disable-line no-redeclare
544
542
  const msgs = []; let isUserMsg = true;
545
543
  chatDivs.forEach((div) => {
546
544
  const sender = isUserMsg ? 'USER' : 'CHATGPT'; isUserMsg = !isUserMsg;
547
- let msg = Array.from(div.childNodes).map(node => node.innerText)
548
- .join('\n\n') // insert double line breaks between paragraphs
549
- .replace('Copy code', '');
545
+ const msg = Array.from(div.childNodes).map(node => node.innerText)
546
+ .join('\n\n') // insert double line breaks between paragraphs
547
+ .replace('Copy code', '');
550
548
  msgs.push(sender + ': ' + msg);
551
549
  });
552
550
  transcript = msgs.join('\n\n');
@@ -567,7 +565,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
567
565
  // Format filename after <title>
568
566
  const parser = new DOMParser(),
569
567
  parsedHtml = parser.parseFromString(htmlContent, 'text/html');
570
- filename = parsedHtml.querySelector('title').textContent + '.html';
568
+ filename = `${ parsedHtml.querySelector('title').textContent || 'ChatGPT conversation' }.html`;
571
569
 
572
570
  // Convert relative CSS paths to absolute ones
573
571
  const cssLinks = parsedHtml.querySelectorAll('link[rel="stylesheet"]');
@@ -864,15 +862,15 @@ const chatgpt = { // eslint-disable-line no-redeclare
864
862
  return formBtnSVG.parentNode.parentNode;
865
863
  }},
866
864
 
867
- getFooterDiv() { return document.querySelector('main form').parentNode.parentNode.nextElementSibling; },
865
+ getFooterDiv() { return document.querySelector('main form')?.parentNode.parentNode.nextElementSibling; },
868
866
  getHeaderDiv() { return document.querySelector('main .sticky'); },
869
867
  getLastPrompt() { return chatgpt.getChatData('active', 'msg', 'user', 'latest'); },
870
868
  getLastResponse() { return chatgpt.getChatData('active', 'msg', 'chatgpt', 'latest'); },
871
869
 
872
870
  getNewChatButton() {
873
871
  for (const navBtnSVG of document.querySelectorAll('nav button svg'))
874
- if (navBtnSVG.querySelector('path[d*="M15.673 3.913a3.121"], ' // pencil-on-pad icon
875
- + 'path[d*="M3.07 10.876C3.623"]')) // refresh icon if temp chat
872
+ if (navBtnSVG.querySelector('path[d^="M15.6729"], ' // pencil-on-pad icon
873
+ + 'path[d^="M3.06957"]')) // refresh icon if temp chat
876
874
  return navBtnSVG.parentNode;
877
875
  },
878
876
 
@@ -1134,7 +1132,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1134
1132
  const optionButtons = document.querySelectorAll('a[role="menuitem"]');
1135
1133
  let cssClasses;
1136
1134
 
1137
- for (let navLink of optionButtons)
1135
+ for (const navLink of optionButtons)
1138
1136
  if (navLink.textContent == 'Settings') {
1139
1137
  cssClasses = navLink.classList;
1140
1138
  break; }
@@ -1152,7 +1150,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1152
1150
  this.elements.push(newElement);
1153
1151
  const menuBtn = document.querySelector('nav button[id*="headless"]');
1154
1152
  if (!this.addedEvent) { // to prevent adding more than one event
1155
- menuBtn.addEventListener('click', () => { setTimeout(addElementsToMenu, 25); });
1153
+ menuBtn?.addEventListener('click', () => { setTimeout(addElementsToMenu, 25); });
1156
1154
  this.addedEvent = true; }
1157
1155
 
1158
1156
  return newElement.id; // Return the element id
@@ -1171,7 +1169,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1171
1169
 
1172
1170
  minify() { chatgpt.code.minify(); },
1173
1171
 
1174
- async notify(msg, position, notifDuration, shadow) {
1172
+ notify(msg, position, notifDuration, shadow) {
1175
1173
  notifDuration = notifDuration ? +notifDuration : 1.75; // sec duration to maintain notification visibility
1176
1174
  const fadeDuration = 0.35, // sec duration of fade-out
1177
1175
  vpYoffset = 23, vpXoffset = 27; // px offset from viewport border
@@ -1185,7 +1183,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1185
1183
 
1186
1184
  // Create/append close button
1187
1185
  const closeBtn = document.createElement('div');
1188
- closeBtn.title = 'Dismiss'; closeBtn.classList.add('notif-close-btn');
1186
+ closeBtn.title = 'Dismiss'; closeBtn.classList.add('notif-close-btn', 'no-mobile-tap-outline');
1189
1187
  const closeSVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
1190
1188
  closeSVG.setAttribute('height', '8px');
1191
1189
  closeSVG.setAttribute('viewBox', '0 0 14 14');
@@ -1215,6 +1213,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1215
1213
  }
1216
1214
  notifStyle.innerText = ( // update prev/new style contents
1217
1215
  '.chatgpt-notif {'
1216
+ + '.no-mobile-tap-outline { outline: none ; -webkit-tap-highlight-color: transparent }'
1218
1217
  + 'background-color: black ; padding: 10px 13px 10px 18px ; border-radius: 11px ; border: 1px solid #f5f5f7 ;' // bubble style
1219
1218
  + 'opacity: 0 ; position: fixed ; z-index: 9999 ; font-size: 1.8rem ; color: white ;' // visibility
1220
1219
  + '-webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ;'
@@ -1270,15 +1269,17 @@ const chatgpt = { // eslint-disable-line no-redeclare
1270
1269
  clearTimeout(dismissFuncTID);
1271
1270
  };
1272
1271
  const dismissFuncTID = setTimeout(dismissNotif, hideDelay * 1000); // maintain visibility for `hideDelay` secs, then dismiss
1273
- closeSVG.addEventListener('click', dismissNotif, { once: true }); // add to close button clicks
1272
+ closeSVG.onclick = dismissNotif; // add to close button clicks
1274
1273
 
1275
1274
  // Destroy notification
1276
- notificationDiv.addEventListener('animationend', () => {
1275
+ notificationDiv.onanimationend = () => {
1277
1276
  notificationDiv.remove(); // remove from DOM
1278
1277
  notifyProps = JSON.parse(localStorage.notifyProps);
1279
1278
  notifyProps.queue[notificationDiv.quadrant].shift(); // + memory
1280
1279
  localStorage.notifyProps = JSON.stringify(notifyProps); // + storage
1281
- }, { once: true });
1280
+ };
1281
+
1282
+ return notificationDiv;
1282
1283
  },
1283
1284
 
1284
1285
  obfuscate() { chatgpt.code.obfuscate(); },
@@ -1437,36 +1438,35 @@ const chatgpt = { // eslint-disable-line no-redeclare
1437
1438
  const responseDivs = document.querySelectorAll('div[data-testid*="conversation-turn"]:nth-child(odd)'),
1438
1439
  strPos = pos.toString().toLowerCase();
1439
1440
  let response = '';
1440
- if (responseDivs.length) {
1441
- if (/last|final/.test(strPos)) // get last response
1442
- response = responseDivs[responseDivs.length - 1].textContent;
1443
- else { // get nth response
1444
- const nthOfResponse = (
1445
-
1446
- // Calculate base number
1447
- Number.isInteger(pos) ? pos : // do nothing for integers
1448
- /^\d+/.test(strPos) ? /^\d+/.exec(strPos)[0] : // extract first digits for strings w/ them
1449
- ( // convert words to integers for digitless strings
1450
- /^(?:1|one|fir)(?:st)?$/.test(strPos) ? 1
1451
- : /^(?:2|tw(?:o|en|el(?:ve|f))|seco)(?:nd|t[yi])?(?:e?th)?$/.test(strPos) ? 2
1452
- : /^(?:3|th(?:ree|ir?))(?:rd|teen|t[yi])?(?:e?th)?$/.test(strPos) ? 3
1453
- : /^(?:4|fou?r)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 4
1454
- : /^(?:5|fi(?:ve|f))(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 5
1455
- : /^(?:6|six)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 6
1456
- : /^(?:7|seven)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 7
1457
- : /^(?:8|eight?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 8
1458
- : /^(?:9|nine?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 9
1459
- : /^(?:10|ten)(?:th)?$/.test(strPos) ? 10 : 1 )
1460
-
1461
- // Transform base number if suffixed
1462
- * ( /(ty|ieth)$/.test(strPos) ? 10 : 1 ) // x 10 if -ty/ieth
1463
- + ( /teen(th)?$/.test(strPos) ? 10 : 0 ) // + 10 if -teen/teenth
1464
-
1465
- );
1466
- response = responseDivs[nthOfResponse - 1].textContent;
1467
- }
1468
- response = response.replace(/^ChatGPT(?:ChatGPT)?/, ''); // strip sender name
1441
+ if (!responseDivs.length) return console.error('No conversation found!');
1442
+ if (/last|final/.test(strPos)) // get last response
1443
+ response = responseDivs[responseDivs.length - 1].textContent;
1444
+ else { // get nth response
1445
+ const nthOfResponse = (
1446
+
1447
+ // Calculate base number
1448
+ Number.isInteger(pos) ? pos : // do nothing for integers
1449
+ /^\d+/.test(strPos) ? /^\d+/.exec(strPos)[0] : // extract first digits for strings w/ them
1450
+ ( // convert words to integers for digitless strings
1451
+ /^(?:1|one|fir)(?:st)?$/.test(strPos) ? 1
1452
+ : /^(?:2|tw(?:o|en|el(?:ve|f))|seco)(?:nd|t[yi])?(?:e?th)?$/.test(strPos) ? 2
1453
+ : /^(?:3|th(?:ree|ir?))(?:rd|teen|t[yi])?(?:e?th)?$/.test(strPos) ? 3
1454
+ : /^(?:4|fou?r)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 4
1455
+ : /^(?:5|fi(?:ve|f))(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 5
1456
+ : /^(?:6|six)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 6
1457
+ : /^(?:7|seven)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 7
1458
+ : /^(?:8|eight?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 8
1459
+ : /^(?:9|nine?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 9
1460
+ : /^(?:10|ten)(?:th)?$/.test(strPos) ? 10 : 1 )
1461
+
1462
+ // Transform base number if suffixed
1463
+ * ( /(ty|ieth)$/.test(strPos) ? 10 : 1 ) // x 10 if -ty/ieth
1464
+ + ( /teen(th)?$/.test(strPos) ? 10 : 0 ) // + 10 if -teen/teenth
1465
+
1466
+ );
1467
+ response = responseDivs[nthOfResponse - 1].textContent;
1469
1468
  }
1469
+ response = response.replace(/^ChatGPT(?:ChatGPT)?/, ''); // strip sender name
1470
1470
  return response;
1471
1471
  },
1472
1472
 
@@ -1481,7 +1481,8 @@ const chatgpt = { // eslint-disable-line no-redeclare
1481
1481
  send(msg, method='') {
1482
1482
  for (let i = 0; i < arguments.length; i++) if (typeof arguments[i] !== 'string')
1483
1483
  return console.error(`Argument ${ i + 1 } must be a string!`);
1484
- const textArea = document.querySelector('form textarea');
1484
+ const textArea = chatgpt.getChatBox();
1485
+ if (!textArea) return console.error('Chatbar element not found!');
1485
1486
  textArea.value = msg;
1486
1487
  textArea.dispatchEvent(new Event('input', { bubbles: true })); // enable send button
1487
1488
  setTimeout(function delaySend() {
@@ -1653,8 +1654,9 @@ const chatgpt = { // eslint-disable-line no-redeclare
1653
1654
  element.style.margin = '2px 0';
1654
1655
  });
1655
1656
 
1656
- const navBar = document.querySelector('nav');
1657
1657
  // Create MutationObserver instance
1658
+ const navBar = document.querySelector('nav');
1659
+ if (!navBar) return console.error('Sidebar element not found!');
1658
1660
  this.observer = new MutationObserver(mutations => {
1659
1661
  mutations.forEach(mutation => {
1660
1662
  if ((mutation.type == 'childList' && mutation.addedNodes.length) ||
@@ -1740,6 +1742,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1740
1742
  isOff() { return !this.isOn(); },
1741
1743
  isOn() {
1742
1744
  const sidebar = document.querySelector('body script + div > div');
1745
+ if (!sidebar) return console.error('Sidebar element not found!');
1743
1746
  return chatgpt.browser.isMobile() ?
1744
1747
  document.documentElement.style.overflow == 'hidden'
1745
1748
  : sidebar.style.visibility != 'hidden' && sidebar.style.width != '0px';
@@ -1749,7 +1752,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1749
1752
  const isMobileDevice = chatgpt.browser.isMobile(),
1750
1753
  navBtnSelector = isMobileDevice ? 'button' : 'nav button',
1751
1754
  isToggleBtn = isMobileDevice ? () => true // since 1st one is toggle
1752
- : btn => btn.querySelector('svg path[d*="M8.857 3h6.286c1.084"]');
1755
+ : btn => btn.querySelector('svg path[d^="M8.857"]');
1753
1756
  for (const btn of document.querySelectorAll(navBtnSelector))
1754
1757
  if (isToggleBtn(btn)) { btn.click(); return; }
1755
1758
  },
@@ -1,7 +1,13 @@
1
- localStorage.alertQueue=JSON.stringify([]),localStorage.notifyProps=JSON.stringify({queue:{topRight:[],bottomRight:[],bottomLeft:[],topLeft:[]}});const x={openAIaccessToken:{},endpoints:{assets:"https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@5f03341750fd154ae4f3f11d6ce79cc2f68f7068",openAI:{session:"https://chatgpt.com/api/auth/session",chats:"https://chatgpt.com/backend-api/conversations",chat:"https://chatgpt.com/backend-api/conversation",share_create:"https://chatgpt.com/backend-api/share/create",share:"https://chatgpt.com/backend-api/share",instructions:"https://chatgpt.com/backend-api/user_system_messages"}},actAs:function(a){return new Promise((o,r)=>{const s=new XMLHttpRequest;s.open("GET","https://raw.githubusercontent.com/KudoAI/chat-prompts/main/dist/personas.min.json",!0),s.send(),s.onload=()=>{if(200!==s.status)return r("🤖 chatgpt.js >> Request failed. Cannot retrieve prompts data.");var e=JSON.parse(s.responseText).personas;if(a){var t=e.find(e=>e.title.toLowerCase()==a.toLowerCase());if(!t)return r(`🤖 chatgpt.js >> Persona '${a}' was not found!`);x.send(t.prompt,"click"),console.info(`Loading ${a} persona...`),x.isIdle().then(()=>{console.info("Persona activated!")})}else{console.log("\n%c🤖 chatgpt.js personas\n","font-family: sans-serif ; font-size: xxx-large ; font-weight: bold");for(const n of e)console.log("%c"+n.title,"font-family: monospace ; font-size: larger ;")}return o()}})},activateDarkMode:function(){document.documentElement.classList.replace("light","dark"),document.documentElement.style.colorScheme="dark",localStorage.setItem("theme","dark")},activateLightMode:function(){document.documentElement.classList.replace("dark","light"),document.documentElement.style.colorScheme="light",localStorage.setItem("theme","light")},alert:function(e,t,n,o,r){const s=x.isDarkMode()?"dark":"light",a=x.browser.isMobile(),i=document.createElement("div"),c=(i.id=Math.floor(1e6*x.randomFloat())+Date.now(),i.classList.add("chatgpt-modal"),document.createElement("div")),l=document.createElement("h2"),u=document.createElement("p");var d=20231203;let g=document.querySelector("#chatgpt-modal-style");(!g||parseInt(g.getAttribute("last-updated"),10)<d)&&(g||((g=document.createElement("style")).id="chatgpt-modal-style",g.setAttribute("last-updated",d.toString()),document.head.append(g)),g.innerText=".chatgpt-modal {position: fixed ; top: 0 ; left: 0 ; width: 100% ; height: 100% ;background-color: rgba(67, 70, 72, 0) ;transition: background-color 0.05s ease ;display: flex ; justify-content: center ; align-items: center ; z-index: 9999 }.chatgpt-modal > div {opacity: 0 ; transform: translateX(-2px) translateY(5px) ; max-width: 75vw ; word-wrap: break-word ;transition: opacity 0.1s cubic-bezier(.165,.84,.44,1), transform 0.2s cubic-bezier(.165,.84,.44,1) ;"+`background-color: ${"dark"==s?"black":"white"} ;`+("dark"!=s?"border: 1px solid rgba(0, 0, 0, 0.3) ;":"")+"padding: 20px ; margin: 12px 23px ; border-radius: 15px ; box-shadow: 0 30px 60px rgba(0, 0, 0, .12) ; -webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ; }.chatgpt-modal h2 { margin-bottom: 9px }"+`.chatgpt-modal a { color: ${"dark"==s?"#00cfff":"#1e9ebb"}}`+".chatgpt-modal.animated > div { opacity: 1 ; transform: translateX(0) translateY(0) }@keyframes alert-zoom-fade-out { 0% { opacity: 1 ; transform: scale(1) }50% { opacity: 0.25 ; transform: scale(1.05) }100% { opacity: 0 ; transform: scale(1.35) }}.modal-buttons { display: flex ; justify-content: flex-end ; margin: 20px -5px -3px 0 ;"+(a?"flex-direction: column-reverse":"")+"}.chatgpt-modal button {"+`margin-left: ${a?0:10}px ; padding: ${a?15:4}px 18px ; border-radius: 15px ;`+(a?"margin-top: 5px ; margin-bottom: 3px ;":"")+`border: 1px solid ${"dark"==s?"white":"black"}}`+".primary-modal-btn {"+`border: 1px solid ${"dark"==s?"white":"black"} ;`+`background: ${"dark"==s?"white":"black"} ;`+`color: ${"dark"==s?"black":"white"}}`+".chatgpt-modal button:hover { color: #3d5d71 ; border-color: #6d9cb9 ;background-color: "+("dark"==s?"#00cfff":"#9cdaff")+";box-shadow: 2px 1px "+("dark"==s?"54px #00cfff":"30px #9cdaff")+"}.modal-close-btn {cursor: pointer ; width: 29px ; height: 29px ; border-radius: 17px ;float: right ; position: relative ; right: -6px ; top: -5px }.modal-close-btn svg { margin: 10px }"+`.modal-close-btn:hover { background-color: #f2f2f2${"dark"==s?"00":""}}`+".chatgpt-modal .checkbox-group { display: flex ; margin-top: -18px }.chatgpt-modal .checkbox-group label {font-size: .7rem ; margin: -.04rem 0 0px .3rem ;"+`color: ${"dark"==s?"#e1e1e1":"#1e1e1e"}}`+'.chatgpt-modal input[type="checkbox"] { transform: scale(0.7) ;'+`border: 1px solid ${"dark"==s?"white":"black"}}`+'.chatgpt-modal input[type="checkbox"]:checked {'+`border: 1px solid ${"dark"==s?"white":"black"} ;`+'background-color: black ; position: inherit }.chatgpt-modal input[type="checkbox"]:focus { outline: none ; box-shadow: none }'),l.innerText=e||"",u.innerText=t||"",x.renderHTML(u);const p=document.createElement("div");p.classList.add("modal-buttons"),n&&(n=Array.isArray(n)?n:[n]).forEach(e=>{var t=document.createElement("button");t.textContent=e.name.replace(/[_-]\w/g,e=>e.slice(1).toUpperCase()).replace(/([A-Z])/g," $1").replace(/^\w/,e=>e.toUpperCase()),t.addEventListener("click",()=>{v(),e()}),p.insertBefore(t,p.firstChild)});d=document.createElement("button"),d.textContent=n?"Dismiss":"OK",p.insertBefore(d,p.firstChild),p.lastChild.classList.add("primary-modal-btn"),e=document.createElement("div");if(o){e.classList.add("checkbox-group");const w=o,b=document.createElement("input");b.type="checkbox",b.addEventListener("change",w);t=document.createElement("label");t.addEventListener("click",()=>{b.checked=!b.checked,w()}),t.textContent=w.name.charAt(0).toUpperCase()+w.name.slice(1).replace(/([A-Z])/g,(e,t)=>" "+t.toLowerCase()).replace(/\b(\w+)nt\b/gi,"$1n't").trim(),e.append(b),e.append(t)}n=document.createElement("div"),n.title="Close",n.classList.add("modal-close-btn"),o=document.createElementNS("http://www.w3.org/2000/svg","svg"),o.setAttribute("height","10px"),o.setAttribute("viewBox","0 0 14 14"),o.setAttribute("fill","none"),t=document.createElementNS("http://www.w3.org/2000/svg","path");t.setAttribute("fill-rule","evenodd"),t.setAttribute("clip-rule","evenodd"),t.setAttribute("fill",x.isDarkMode()?"white":"black"),t.setAttribute("d","M13.7071 1.70711C14.0976 1.31658 14.0976 0.683417 13.7071 0.292893C13.3166 -0.0976312 12.6834 -0.0976312 12.2929 0.292893L7 5.58579L1.70711 0.292893C1.31658 -0.0976312 0.683417 -0.0976312 0.292893 0.292893C-0.0976312 0.683417 -0.0976312 1.31658 0.292893 1.70711L5.58579 7L0.292893 12.2929C-0.0976312 12.6834 -0.0976312 13.3166 0.292893 13.7071C0.683417 14.0976 1.31658 14.0976 1.70711 13.7071L7 8.41421L12.2929 13.7071C12.6834 14.0976 13.3166 14.0976 13.7071 13.7071C14.0976 13.3166 14.0976 12.6834 13.7071 12.2929L8.41421 7L13.7071 1.70711Z"),o.append(t),n.append(o),[n,l,u,p,e].forEach(e=>{c.append(e)}),c.style.width=`${r||458}px`,i.append(c),document.body.append(i);let f=JSON.parse(localStorage.alertQueue);f.push(i.id),localStorage.alertQueue=JSON.stringify(f),i.style.display="none",1===f.length&&(i.style.display="",setTimeout(()=>{i.style.backgroundColor=`rgba(67, 70, 72, ${"dark"==s?.62:.1})`,i.classList.add("animated")},100));const m=e=>{(e.target==e.currentTarget||e.target instanceof SVGPathElement)&&v()},h=e=>{if([" ","Spacebar","Enter","Return","Escape","Esc"].includes(e.key)||[32,13,27].includes(e.keyCode))for(const n of f){var t=document.getElementById(n);if(t&&"none"!==t.style.display)return void(e.key.includes("Esc")||27==e.keyCode?v():([" ","Spacebar","Enter","Return"].includes(e.key)||[32,13].includes(e.keyCode))&&(t=t.querySelector(".modal-buttons").lastChild)&&(t.click(),e.preventDefault()))}},y=[i,n,o,d],v=(y.forEach(e=>{e.addEventListener("click",m)}),document.addEventListener("keydown",h),()=>{i.style.backgroundColor="transparent",c.style.animation="alert-zoom-fade-out 0.075s ease-out",setTimeout(()=>{if(i.remove(),(f=JSON.parse(localStorage.alertQueue)).shift(),localStorage.alertQueue=JSON.stringify(f),y.forEach(e=>{e.removeEventListener("click",m)}),document.removeEventListener("keydown",h),0<f.length){const e=document.getElementById(f[0]);setTimeout(()=>{e.style.display="",setTimeout(()=>{e.classList.add("animated")},100)},500)}},50)});return i.id},askAndGetReply:async function(e){return x.send(e),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")},autoRefresh:{activate:function(e){if(this.isActive)console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Auto refresh already active!");else{const n=this,o=(this.toggle.refreshFrame(),t=>{var e=Math.max(2,Math.floor(21*x.randomFloat()-10));n.isActive=setTimeout(()=>{var e=document.querySelector('script[src*="_ssgManifest.js"]');document.querySelector("#refresh-frame").src=e.src+"?"+Date.now(),console.log("↻ ChatGPT >> ["+n.nowTimeStamp()+"] ChatGPT session refreshed"),o(t)},1e3*(t+e))});o(e?parseInt(e,10):30),console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Auto refresh activated"),navigator.userAgent.includes("Chrome")&&void 0!==document.hidden&&document.addEventListener("visibilitychange",this.toggle.beacons)}},deactivate:function(){this.isActive?(this.toggle.refreshFrame(),document.removeEventListener("visibilitychange",this.toggle.beacons),clearTimeout(this.isActive),this.isActive=null,console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Auto refresh de-activated")):console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Auto refresh already inactive!")},nowTimeStamp:function(){var e=new Date,t=e.getHours()%12||12;let n=e.getMinutes(),o=e.getSeconds();n<10&&(n="0"+n),o<10&&(o="0"+o);e=e.getHours()<12?"AM":"PM";return t+":"+n+":"+o+" "+e},toggle:{beacons:function(){x.autoRefresh.beaconID?(clearInterval(x.autoRefresh.beaconID),x.autoRefresh.beaconID=null,console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Beacons de-activated")):(x.autoRefresh.beaconID=setInterval(()=>{navigator.sendBeacon("https://httpbin.org/post",new Uint8Array),console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Beacon sent")},9e4),console.log("↻ ChatGPT >> ["+x.autoRefresh.nowTimeStamp()+"] Beacons activated"))},refreshFrame:function(){let e=document.querySelector("#refresh-frame");e?e.remove():(e=Object.assign(document.createElement("iframe"),{id:"refresh-frame",style:"display: none"}),document.head.prepend(e))}}},browser:{isLightMode:function(){return window.matchMedia?.("(prefers-color-scheme: light)")?.matches},isDarkMode:function(){return window.matchMedia?.("(prefers-color-scheme: dark)")?.matches},isChromium:function(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Chromium")},isChrome:function(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Chrome")},isEdge:function(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Edge")},isBrave:function(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Brave")},isFirefox:function(){return navigator.userAgent.includes("Firefox")},isFullScreen:function(){var e=navigator.userAgent;return e.includes("Chrome")?window.matchMedia("(display-mode: fullscreen)").matches:e.includes("Firefox")?window.fullScreen:/MSIE|rv:/.test(e)?document.msFullscreenElement:document.webkitIsFullScreen},isMobile:function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}},clearChats:async function(){return new Promise((n,o)=>{x.getAccessToken().then(e=>{const t=new XMLHttpRequest;t.open("PATCH",x.endpoints.openAI.chats,!0),t.setRequestHeader("Content-Type","application/json"),t.setRequestHeader("Authorization","Bearer "+e),t.onload=()=>{if(200!==t.status)return o("🤖 chatgpt.js >> Request failed. Cannot clear chats.");console.info("Chats successfully cleared"),n()},t.send(JSON.stringify({is_visible:!1}))}).catch(e=>o(new Error(e.message)))})},code:{execute:async function(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(x.send("Display the output as if you were terminal:\n\n"+e),console.info("Executing code..."),await x.isIdle(),x.code.extract(await x.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},extract:function(e){var t=e.match(/(?<=```.*\n)[\s\S]*?(?=```)/g);return t?t[t.length-1]:e},isIdle:async function(){await new Promise(t=>{!function e(){document.querySelector("div[data-message-author-role]")?t(!0):setTimeout(e,200)}()}),await new Promise(n=>{!function e(){var t=document.querySelectorAll("div[data-message-author-role]");"assistant"==t[t.length-1].dataset.messageAuthorRole?n(!0):setTimeout(e,200)}()});const n=await new Promise(n=>{!function e(){var t=document.querySelectorAll('div[data-message-author-role="assistant"]'),t=t[t.length-1];t.querySelector("pre")?n(t):setTimeout(e,200)}()});return Promise.race([new Promise(t=>{!function e(){n.querySelector("pre").nextElementSibling?t(!0):setTimeout(e,200)}()}),x.isIdle()])},minify:async function(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(x.send("Minify the following code:\n\n"+e),console.info("Minifying code..."),await x.isIdle(),x.code.extract(await x.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},obfuscate:async function(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(x.send("Obfuscate the following code:\n\n"+e),console.info("Obfuscating code..."),await x.isIdle(),x.code.extract(await x.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},refactor:async function(e,t){if(!e)return console.error("Code (1st) argument not supplied. Pass some code!");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return x.send("Refactor the following code for "+(t||"brevity")+":\n\n"+e),console.info("Refactoring code..."),await x.isIdle(),x.code.extract(await x.getChatData("active","msg","chatgpt","latest"))},review:async function(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(x.send("Review the following code for me:\n\n"+e),console.info("Reviewing code..."),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")):console.error("Code argument not supplied. Pass some code!")},unminify:async function(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(x.send("Unminify the following code.:\n\n"+e),console.info("Unminifying code..."),await x.isIdle(),x.code.extract(await x.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},write:async function(e,t){if(!e)return console.error("Prompt (1st) argument not supplied. Pass a prompt!");if(!t)return console.error("outputLang (2nd) argument not supplied. Pass a language!");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return x.send(e+"\n\nWrite this as code in "+t),console.info("Writing code..."),await x.isIdle(),x.code.extract(await x.getChatData("active","msg","chatgpt","latest"))}},continue:function(){x.response.continue()},detectLanguage:async function(e){return e?"string"!=typeof e?console.error("Text argument must be a string!"):(x.send("Detect the language of the following text:\n\n"+e+"\n\nOnly respond with the name of the language"),console.info("Reviewing text..."),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")):console.error("Text argument not supplied. Pass some text!")},executeCode:function(){x.code.execute()},exportChat:async function(e,t){e=e?Number.isInteger(e)||/^\d+$/.test(e)?parseInt(e,10):e:"active",t=t.toLowerCase()||"html",console.info("Generating transcript...");let o="",n;if(/te?xt/.test(t)){var r=new Date,s=r.getDate().toString().padStart(2,"0"),a=(r.getMonth()+1).toString().padStart(2,"0"),i=r.getFullYear(),c=r.getHours().toString().padStart(2,"0"),r=r.getMinutes().toString().padStart(2,"0");if(n=`ChatGPT_${s}-${a}-${i}_${c}-${r}.txt`,"active"==e&&/\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/.test(window.location.href)){s=document.querySelectorAll("main > div > div > div > div > div > div[class*=group]");if(0===s.length)return console.error("Chat is empty!");const l=[];let n=!0;s.forEach(e=>{var t=n?"USER":"CHATGPT",e=(n=!n,Array.from(e.childNodes).map(e=>e.innerText).join("\n\n").replace("Copy code",""));l.push(t+": "+e)}),o=l.join("\n\n")}else for(const u of await x.getChatData(e,"msg","both","all"))o=(o+=`USER: ${u.user}
1
+ /**
2
+ * © 2023–2024 KudoAI & contributors under the MIT license.
3
+ * Source: https://github.com/KudoAI/chatgpt.js
4
+ * User guide: https://chatgptjs.org/userguide
5
+ * Latest minified release: https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js/chatgpt.min.js
6
+ */
7
+ localStorage.alertQueue=JSON.stringify([]),localStorage.notifyProps=JSON.stringify({queue:{topRight:[],bottomRight:[],bottomLeft:[],topLeft:[]}});let chatgpt={openAIaccessToken:{},endpoints:{assets:"https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@6aaa431774f5e07d91fdbd4232d0588cd4beb464",openAI:{session:"https://chatgpt.com/api/auth/session",chats:"https://chatgpt.com/backend-api/conversations",chat:"https://chatgpt.com/backend-api/conversation",share_create:"https://chatgpt.com/backend-api/share/create",share:"https://chatgpt.com/backend-api/share",instructions:"https://chatgpt.com/backend-api/user_system_messages"}},actAs(s){return new Promise((o,a)=>{let n=new XMLHttpRequest;n.open("GET","https://raw.githubusercontent.com/KudoAI/chat-prompts/main/dist/personas.min.json",!0),n.send(),n.onload=()=>{if(200!==n.status)return a("🤖 chatgpt.js >> Request failed. Cannot retrieve prompts data.");var e=JSON.parse(n.responseText).personas;if(s){var t=e.find(e=>e.title.toLowerCase()==s.toLowerCase());if(!t)return a(`🤖 chatgpt.js >> Persona '${s}' was not found!`);chatgpt.send(t.prompt,"click"),console.info(`Loading ${s} persona...`),chatgpt.isIdle().then(()=>{console.info("Persona activated!")})}else{console.log("\n%c🤖 chatgpt.js personas\n","font-family: sans-serif ; font-size: xxx-large ; font-weight: bold");for(var r of e)console.log("%c"+r.title,"font-family: monospace ; font-size: larger ;")}return o()}})},activateDarkMode(){document.documentElement.classList.replace("light","dark"),document.documentElement.style.colorScheme="dark",localStorage.setItem("theme","dark")},activateLightMode(){document.documentElement.classList.replace("dark","light"),document.documentElement.style.colorScheme="light",localStorage.setItem("theme","light")},alert(r,o,e,a,t){let n=chatgpt.isDarkMode()?"dark":"light",s=chatgpt.browser.isMobile(),i=document.createElement("div"),c=(i.id=Math.floor(1e6*chatgpt.randomFloat())+Date.now(),i.classList.add("chatgpt-modal"),document.createElement("div")),l=document.createElement("h2"),d=document.createElement("p");var g=20231203;let u=document.querySelector("#chatgpt-modal-style"),p=((!u||parseInt(u.getAttribute("last-updated"),10)<g)&&(u||((u=document.createElement("style")).id="chatgpt-modal-style",u.setAttribute("last-updated",g.toString()),document.head.append(u)),u.innerText=".no-mobile-tap-outline { outline: none ; -webkit-tap-highlight-color: transparent }.chatgpt-modal {position: fixed ; top: 0 ; left: 0 ; width: 100% ; height: 100% ;background-color: rgba(67, 70, 72, 0) ;transition: background-color 0.05s ease ;display: flex ; justify-content: center ; align-items: center ; z-index: 9999 }.chatgpt-modal > div {opacity: 0 ; transform: translateX(-2px) translateY(5px) ; max-width: 75vw ; word-wrap: break-word ;transition: opacity 0.1s cubic-bezier(.165,.84,.44,1), transform 0.2s cubic-bezier(.165,.84,.44,1) ;"+`background-color: ${"dark"==n?"black":"white"} ;`+("dark"!=n?"border: 1px solid rgba(0, 0, 0, 0.3) ;":"")+"padding: 20px ; margin: 12px 23px ; border-radius: 15px ; box-shadow: 0 30px 60px rgba(0, 0, 0, .12) ; -webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ; }.chatgpt-modal h2 { margin-bottom: 9px }"+`.chatgpt-modal a { color: ${"dark"==n?"#00cfff":"#1e9ebb"}}`+".chatgpt-modal.animated > div { opacity: 1 ; transform: translateX(0) translateY(0) }@keyframes alert-zoom-fade-out { 0% { opacity: 1 ; transform: scale(1) }50% { opacity: 0.25 ; transform: scale(1.05) }100% { opacity: 0 ; transform: scale(1.35) }}.modal-buttons { display: flex ; justify-content: flex-end ; margin: 20px -5px -3px 0 ;"+(s?"flex-direction: column-reverse":"")+"}.chatgpt-modal button {"+`margin-left: ${s?0:10}px ; padding: ${s?15:4}px 18px ; border-radius: 15px ;`+(s?"margin-top: 5px ; margin-bottom: 3px ;":"")+`border: 1px solid ${"dark"==n?"white":"black"}}`+".primary-modal-btn {"+`border: 1px solid ${"dark"==n?"white":"black"} ;`+`background: ${"dark"==n?"white":"black"} ;`+`color: ${"dark"==n?"black":"white"}}`+".chatgpt-modal button:hover { color: #3d5d71 ; border-color: #6d9cb9 ;background-color: "+("dark"==n?"#00cfff":"#9cdaff")+";box-shadow: 2px 1px "+("dark"==n?"54px #00cfff":"30px #9cdaff")+"}.modal-close-btn {cursor: pointer ; width: 29px ; height: 29px ; border-radius: 17px ;float: right ; position: relative ; right: -6px ; top: -5px }.modal-close-btn svg { margin: 10px }"+`.modal-close-btn:hover { background-color: #f2f2f2${"dark"==n?"00":""}}`+".chatgpt-modal .checkbox-group { display: flex ; margin-top: -18px }.chatgpt-modal .checkbox-group label {font-size: .7rem ; margin: -.04rem 0 0px .3rem ;"+`color: ${"dark"==n?"#e1e1e1":"#1e1e1e"}}`+'.chatgpt-modal input[type="checkbox"] { transform: scale(0.7) ;'+`border: 1px solid ${"dark"==n?"white":"black"}}`+'.chatgpt-modal input[type="checkbox"]:checked {'+`border: 1px solid ${"dark"==n?"white":"black"} ;`+'background-color: black ; position: inherit }.chatgpt-modal input[type="checkbox"]:focus { outline: none ; box-shadow: none }'),l.innerText=r||"",d.innerText=o||"",chatgpt.renderHTML(d),document.createElement("div"));p.classList.add("modal-buttons","no-mobile-tap-outline"),e&&(e=Array.isArray(e)?e:[e]).forEach(e=>{var t=document.createElement("button");t.textContent=e.name.replace(/[_-]\w/g,e=>e.slice(1).toUpperCase()).replace(/([A-Z])/g," $1").replace(/^\w/,e=>e.toUpperCase()),t.onclick=()=>{y(),e()},p.insertBefore(t,p.firstChild)});g=document.createElement("button"),g.textContent=e?"Dismiss":"OK",p.insertBefore(g,p.firstChild),p.lastChild.classList.add("primary-modal-btn"),r=document.createElement("div");if(a){r.classList.add("checkbox-group");let e=a,t=document.createElement("input");t.type="checkbox",t.onchange=e;o=document.createElement("label");o.onclick=()=>{t.checked=!t.checked,e()},o.textContent=e.name.charAt(0).toUpperCase()+e.name.slice(1).replace(/([A-Z])/g,(e,t)=>" "+t.toLowerCase()).replace(/\b(\w+)nt\b/gi,"$1n't").trim(),r.append(t),r.append(o)}e=document.createElement("div"),e.title="Close",e.classList.add("modal-close-btn","no-mobile-tap-outline"),a=document.createElementNS("http://www.w3.org/2000/svg","svg"),a.setAttribute("height","10px"),a.setAttribute("viewBox","0 0 14 14"),a.setAttribute("fill","none"),o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("fill-rule","evenodd"),o.setAttribute("clip-rule","evenodd"),o.setAttribute("fill",chatgpt.isDarkMode()?"white":"black"),o.setAttribute("d","M13.7071 1.70711C14.0976 1.31658 14.0976 0.683417 13.7071 0.292893C13.3166 -0.0976312 12.6834 -0.0976312 12.2929 0.292893L7 5.58579L1.70711 0.292893C1.31658 -0.0976312 0.683417 -0.0976312 0.292893 0.292893C-0.0976312 0.683417 -0.0976312 1.31658 0.292893 1.70711L5.58579 7L0.292893 12.2929C-0.0976312 12.6834 -0.0976312 13.3166 0.292893 13.7071C0.683417 14.0976 1.31658 14.0976 1.70711 13.7071L7 8.41421L12.2929 13.7071C12.6834 14.0976 13.3166 14.0976 13.7071 13.7071C14.0976 13.3166 14.0976 12.6834 13.7071 12.2929L8.41421 7L13.7071 1.70711Z"),a.append(o),e.append(a),[e,l,d,p,r].forEach(e=>{c.append(e)}),c.style.width=`${t||458}px`,i.append(c),document.body.append(i);let h=JSON.parse(localStorage.alertQueue),m=(h.push(i.id),localStorage.alertQueue=JSON.stringify(h),i.style.display="none",1===h.length&&(i.style.display="",setTimeout(()=>{i.style.backgroundColor=`rgba(67, 70, 72, ${"dark"==n?.62:.1})`,i.classList.add("animated")},100)),e=>{(e.target==e.currentTarget||e.target instanceof SVGPathElement)&&y()}),f=e=>{if([" ","Spacebar","Enter","Return","Escape","Esc"].includes(e.key)||[32,13,27].includes(e.keyCode))for(var t of h){var t=document.getElementById(t);if(t&&"none"!==t.style.display)return void(e.key.includes("Esc")||27==e.keyCode?y():([" ","Spacebar","Enter","Return"].includes(e.key)||[32,13].includes(e.keyCode))&&(t=t.querySelector(".modal-buttons").lastChild)&&(t.click(),e.preventDefault()))}},y=([i,e,a,g].forEach(e=>e.onclick=m),document.addEventListener("keydown",f),()=>{i.style.backgroundColor="transparent",c.style.animation="alert-zoom-fade-out 0.075s ease-out",setTimeout(()=>{if(i.remove(),(h=JSON.parse(localStorage.alertQueue)).shift(),localStorage.alertQueue=JSON.stringify(h),document.removeEventListener("keydown",f),0<h.length){let e=document.getElementById(h[0]);setTimeout(()=>{e.style.display="",setTimeout(()=>{e.classList.add("animated")},100)},500)}},50)});return i.id},async askAndGetReply(e){return chatgpt.send(e),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")},autoRefresh:{activate(e){if(this.isActive)console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Auto refresh already active!");else{let r=this,o=(this.toggle.refreshFrame(),t=>{var e=Math.max(2,Math.floor(21*chatgpt.randomFloat()-10));r.isActive=setTimeout(()=>{var e=document.querySelector('script[src*="_ssgManifest.js"]');e&&(document.querySelector("#refresh-frame").src=e.src+"?"+Date.now(),console.log("↻ ChatGPT >> ["+r.nowTimeStamp()+"] ChatGPT session refreshed")),o(t)},1e3*(t+e))});o(e?parseInt(e,10):30),console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Auto refresh activated"),navigator.userAgent.includes("Chrome")&&void 0!==document.hidden&&document.addEventListener("visibilitychange",this.toggle.beacons)}},deactivate(){this.isActive?(this.toggle.refreshFrame(),document.removeEventListener("visibilitychange",this.toggle.beacons),clearTimeout(this.isActive),this.isActive=null,console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Auto refresh de-activated")):console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Auto refresh already inactive!")},nowTimeStamp(){var e=new Date,t=e.getHours()%12||12;let r=e.getMinutes(),o=e.getSeconds();r<10&&(r="0"+r),o<10&&(o="0"+o);e=e.getHours()<12?"AM":"PM";return t+":"+r+":"+o+" "+e},toggle:{beacons(){chatgpt.autoRefresh.beaconID?(clearInterval(chatgpt.autoRefresh.beaconID),chatgpt.autoRefresh.beaconID=null,console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Beacons de-activated")):(chatgpt.autoRefresh.beaconID=setInterval(()=>{navigator.sendBeacon("https://httpbin.org/post",new Uint8Array),console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Beacon sent")},9e4),console.log("↻ ChatGPT >> ["+chatgpt.autoRefresh.nowTimeStamp()+"] Beacons activated"))},refreshFrame(){let e=document.querySelector("#refresh-frame");e?e.remove():(e=Object.assign(document.createElement("iframe"),{id:"refresh-frame",style:"display: none"}),document.head.prepend(e))}}},browser:{isLightMode(){return window.matchMedia?.("(prefers-color-scheme: light)")?.matches},isDarkMode(){return window.matchMedia?.("(prefers-color-scheme: dark)")?.matches},isChromium(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Chromium")},isChrome(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Chrome")},isEdge(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Edge")},isBrave(){return!!JSON.stringify(navigator.userAgentData?.brands)?.includes("Brave")},isFirefox(){return navigator.userAgent.includes("Firefox")},isFullScreen(){var e=navigator.userAgent;return e.includes("Chrome")?window.matchMedia("(display-mode: fullscreen)").matches:e.includes("Firefox")?window.fullScreen:/MSIE|rv:/.test(e)?document.msFullscreenElement:document.webkitIsFullScreen},isMobile(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}},async clearChats(){return new Promise((r,o)=>{chatgpt.getAccessToken().then(e=>{let t=new XMLHttpRequest;t.open("PATCH",chatgpt.endpoints.openAI.chats,!0),t.setRequestHeader("Content-Type","application/json"),t.setRequestHeader("Authorization","Bearer "+e),t.onload=()=>{if(200!==t.status)return o("🤖 chatgpt.js >> Request failed. Cannot clear chats.");console.info("Chats successfully cleared"),r()},t.send(JSON.stringify({is_visible:!1}))}).catch(e=>o(new Error(e.message)))})},code:{async execute(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(chatgpt.send("Display the output as if you were terminal:\n\n"+e),console.info("Executing code..."),await chatgpt.isIdle(),chatgpt.code.extract(await chatgpt.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},extract(e){var t=e.match(/(?<=```.*\n)[\s\S]*?(?=```)/g);return t?t[t.length-1]:e},async isIdle(){await new Promise(t=>{!function e(){document.querySelector("div[data-message-author-role]")?t(!0):setTimeout(e,200)}()}),await new Promise(r=>{!function e(){var t=document.querySelectorAll("div[data-message-author-role]");"assistant"==t[t.length-1]?.dataset.messageAuthorRole?r(!0):setTimeout(e,200)}()});let r=await new Promise(r=>{!function e(){var t=document.querySelectorAll('div[data-message-author-role="assistant"]'),t=t[t.length-1];t?.querySelector("pre")?r(t):setTimeout(e,200)}()});return Promise.race([new Promise(t=>{!function e(){r?.querySelector("pre").nextElementSibling?t(!0):setTimeout(e,200)}()}),chatgpt.isIdle()])},async minify(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(chatgpt.send("Minify the following code:\n\n"+e),console.info("Minifying code..."),await chatgpt.isIdle(),chatgpt.code.extract(await chatgpt.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},async obfuscate(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(chatgpt.send("Obfuscate the following code:\n\n"+e),console.info("Obfuscating code..."),await chatgpt.isIdle(),chatgpt.code.extract(await chatgpt.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},async refactor(e,t){if(!e)return console.error("Code (1st) argument not supplied. Pass some code!");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return chatgpt.send("Refactor the following code for "+(t||"brevity")+":\n\n"+e),console.info("Refactoring code..."),await chatgpt.isIdle(),chatgpt.code.extract(await chatgpt.getChatData("active","msg","chatgpt","latest"))},async review(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(chatgpt.send("Review the following code for me:\n\n"+e),console.info("Reviewing code..."),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")):console.error("Code argument not supplied. Pass some code!")},async unminify(e){return e?"string"!=typeof e?console.error("Code argument must be a string!"):(chatgpt.send("Unminify the following code.:\n\n"+e),console.info("Unminifying code..."),await chatgpt.isIdle(),chatgpt.code.extract(await chatgpt.getChatData("active","msg","chatgpt","latest"))):console.error("Code argument not supplied. Pass some code!")},async write(e,t){if(!e)return console.error("Prompt (1st) argument not supplied. Pass a prompt!");if(!t)return console.error("outputLang (2nd) argument not supplied. Pass a language!");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return chatgpt.send(e+"\n\nWrite this as code in "+t),console.info("Writing code..."),await chatgpt.isIdle(),chatgpt.code.extract(await chatgpt.getChatData("active","msg","chatgpt","latest"))}},continue(){chatgpt.response.continue()},async detectLanguage(e){return e?"string"!=typeof e?console.error("Text argument must be a string!"):(chatgpt.send("Detect the language of the following text:\n\n"+e+"\n\nOnly respond with the name of the language"),console.info("Reviewing text..."),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")):console.error("Text argument not supplied. Pass some text!")},executeCode(){chatgpt.code.execute()},async exportChat(e,t){e=e?Number.isInteger(e)||/^\d+$/.test(e)?parseInt(e,10):e:"active",t=t.toLowerCase()||"html",console.info("Generating transcript...");let a="",r;if(/te?xt/.test(t)){var o=new Date,n=o.getDate().toString().padStart(2,"0"),s=(o.getMonth()+1).toString().padStart(2,"0"),i=o.getFullYear(),c=o.getHours().toString().padStart(2,"0"),o=o.getMinutes().toString().padStart(2,"0");if(r=`ChatGPT_${n}-${s}-${i}_${c}-${o}.txt`,"active"==e&&/\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/.test(window.location.href)){n=document.querySelectorAll("main > div > div > div > div > div > div[class*=group]");if(0===n.length)return console.error("Chat is empty!");let r=[],o=!0;n.forEach(e=>{var t=o?"USER":"CHATGPT",e=(o=!o,Array.from(e.childNodes).map(e=>e.innerText).join("\n\n").replace("Copy code",""));r.push(t+": "+e)}),a=r.join("\n\n")}else for(var l of await chatgpt.getChatData(e,"msg","both","all"))a=(a+=`USER: ${l.user}
2
8
 
3
- `)+`CHATGPT: ${u.chatgpt}
9
+ `)+`CHATGPT: ${l.chatgpt}
4
10
 
5
- `}else{a=await(await fetch(await x.shareChat(e))).text(),i=(new DOMParser).parseFromString(a,"text/html");n=i.querySelector("title").textContent+".html",i.querySelectorAll('link[rel="stylesheet"]').forEach(e=>{var t=e.getAttribute("href");t?.startsWith("/")&&e.setAttribute("href","https://chat.openai.com"+t)}),o=(new XMLSerializer).serializeToString(i)}if(console.info(`Exporting transcript as ${t.toUpperCase()}...`),"pdf"==t){o=o.replace(/<svg.*?<\/svg>/g,e=>{return`<img src="${"data:image/svg+xml,"+encodeURIComponent(e)}">`});const d=window.open("","","toolbar=0, location=0, menubar=0, height=600, width=800");d.document.write(o),setTimeout(()=>{d.print({toPDF:!0})},100)}else{"md"==t&&(c=/<.*(?:<h1(.|\n)*?href=".*?continue[^"]*".*?\/a>.*?)<[^/]/.exec(o)[1],o=c||o,n=n.replace(".html",".md"));r=new Blob([o],{type:"text/"+("html"==t?"html":"md"==t?"markdown":"plain")}),s=document.createElement("a"),e=URL.createObjectURL(r);s.href=e,s.download=n,document.body.append(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(e)}},extractCode:function(){x.code.extract()},focusChatbar:function(){x.getChatBox()?.focus()},generateRandomIP:function(){var e=Array.from({length:4},()=>Math.floor(256*x.randomFloat())).join(".");return console.info("IP generated: "+e),e},get:function(e,t=""){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid arguments. Both arguments must be strings.");if(!a.includes(e.toLowerCase()))throw new Error("Invalid targetType: "+e+". Valid values are: "+JSON.stringify(a));var n=[],o=new RegExp("^get(.*)"+e+"$","i");for(const s in x)"function"==typeof x[s]&&o.test(s)&&n.push(s.replace(o,"$1").toLowerCase());if(!n.includes(t.toLowerCase()))throw new Error("Invalid targetName: "+t+". "+(0<n.length?"Valid values are: "+JSON.stringify(n):"targetType "+e.toLowerCase()+" does not require additional options."));const r=("get"+t+e).toLowerCase();return this[Object.keys(this).find(e=>e.toLowerCase()==r)]()},getAccessToken:function(){return new Promise((e,t)=>{if(0<Object.keys(x.openAIaccessToken).length&&0<=Date.parse(x.openAIaccessToken.expireDate)-Date.parse(new Date))return e(x.openAIaccessToken.token);const n=new XMLHttpRequest;n.open("GET",x.endpoints.openAI.session,!0),n.setRequestHeader("Content-Type","application/json"),n.onload=()=>200!==n.status?t("🤖 chatgpt.js >> Request failed. Cannot retrieve access token."):(console.info("Token expiration: "+new Date(JSON.parse(n.responseText).expires).toLocaleString().replace(","," at")),x.openAIaccessToken={token:JSON.parse(n.responseText).accessToken,expireDate:JSON.parse(n.responseText).expires},e(x.openAIaccessToken.token)),n.send()})},getAccountDetails:function(...a){var e=["email","id","image","name","picture"];for(const t of a=arguments[0]?Array.isArray(arguments[0])?arguments[0]:Array.from(arguments):e)if(!e.includes(t))return console.error("Invalid detail arg '"+t+"' supplied. Valid details are:\n ["+e+"]");return new Promise((o,r)=>{const s=new XMLHttpRequest;s.open("GET",x.endpoints.openAI.session,!0),s.setRequestHeader("Content-Type","application/json"),s.onload=()=>{if(200!==s.status)return r("🤖 chatgpt.js >> Request failed. Cannot retrieve account details.");var e=JSON.parse(s.responseText).user,t={};for(const n of a)t[n]=e[n];return o(t)},s.send()})},getChatBox:function(){return document.getElementById("prompt-textarea")},getChatData:function(u=1,o="all",p="all",f="all"){var e=["all","id","title","create_time","update_time","msg"],t=["all","both","user","chatgpt"];u=u?Number.isInteger(u)||/^\d+$/.test(u)?0===parseInt(u,10)?0:parseInt(u,10)-1:u:"active",o=["all",""].includes(o)?e.filter(e=>/^(?!all$|msg$).*/.test(e)):Array.isArray(o)?o:[o],p=p?t.includes(p)?p:"invalid":"all",f=Number.isInteger(f)||/^\d+$/.test(f)?0===parseInt(f,10)?0:parseInt(f,10)-1:["all","latest"].includes(f.toLowerCase())?f.toLowerCase():f?"invalid":"all";for(const n of o)if(!e.includes(n))return console.error("Invalid detail arg '"+n+"' passed. Valid details are:\n ["+e+"]");if("invalid"==p)return console.error("Invalid sender arg passed. Valid senders are:\n ["+t+"]");if("invalid"==f)return console.error("Invalid msgToGet arg passed. Valid msg's to get are:\n [ 'all' | 'latest' | index of msg to get ]");const r=(e,c)=>{const l=/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/;return new Promise((t,a)=>{const i=new XMLHttpRequest;i.open("GET",x.endpoints.openAI.chats,!0),i.setRequestHeader("Content-Type","application/json"),i.setRequestHeader("Authorization","Bearer "+e),i.onload=()=>{if(200!==i.status)return a("🤖 chatgpt.js >> Request failed. Cannot retrieve chat details.");var n=JSON.parse(i.responseText).items;if(n.length<=0)return a("🤖 chatgpt.js >> Chat list is empty.");var o={};if(Number.isInteger(u)||"latest"==u||"active"==u&&!new RegExp("/"+l.source+"$").test(window.location.href)){if((u=Number.isInteger(u)?u:0)>n.length)return a("🤖 chatgpt.js >> Chat with index "+(u+1)+" is out of bounds. Only "+n.length+" chats exist!");for(const e of c)o[e]=n[u][e]}else{var r="active"==u||new RegExp("^"+l.source+"$").test(u)?"id":"title";"active"==u&&(u=l.exec(window.location.href)[0]);let e,t;for(e=0;e<n.length;e++)if(n[e][r]==u){t=!0;break}if(!t)return a("🤖 chatgpt.js >> No chat with "+r+" = "+u+" found.");for(const s of c)o[s]=n[e][s]}return t(o)},i.send()})};return new Promise(n=>x.getAccessToken().then(e=>{return n(o.includes("msg")?(t=e,new Promise((u,d)=>{const g=new XMLHttpRequest;r(t,["id"]).then(e=>{g.open("GET",x.endpoints.openAI.chat+"/"+e.id,!0),g.setRequestHeader("Content-Type","application/json"),g.setRequestHeader("Authorization","Bearer "+t),g.onload=()=>{if(200!==g.status)return d("🤖 chatgpt.js >> Request failed. Cannot retrieve chat messages.");var t=JSON.parse(g.responseText).mapping,n=[],o=[],r=[];for(const e in t)null!=t[e].message&&"user"==t[e].message.author.role&&n.push({id:t[e].id,msg:t[e].message});if(n.sort((e,t)=>e.msg.create_time-t.msg.create_time),parseInt(f,10)+1>n.length)return d("🤖 chatgpt.js >> Message/response with index "+(f+1)+" is out of bounds. Only "+n.length+" messages/responses exist!");for(const s of n){let e=[];for(const a in t)null!=t[a].message&&"assistant"==t[a].message.author.role&&t[a].parent==s.id&&e.push(t[a].message);e.sort((e,t)=>e.create_time-t.create_time),e=1===(e=e.map(e=>{switch(e.content.content_type){case"code":return e.content.text;case"text":return e.content.parts[0];default:return}})).length?e[0]:e,o.push(e)}if("user"==p)for(const i in n)r.push(n[i].msg.content.parts[0]);else if("chatgpt"==p)for(const c of o)r.push("latest"==f?o[o.length-1]:c);else{let e=0;for(const l in n)r.push({user:n[l].msg.content.parts[0],chatgpt:"latest"==f?o[e][o[e].length-1]:o[e]}),e++}return u("all"==f?r:"latest"==f?r[r.length-1]:r[f])},g.send()})})):r(e,o));var t}))},getChatInput:function(){return x.getChatBox().value},getContinueGeneratingButton:function(){for(const e of document.querySelectorAll("form button svg"))if(e.querySelector('path[d*="M4.472 2.5a1"]'))return e.parentNode.parentNode},getFooterDiv:function(){return document.querySelector("main form").parentNode.parentNode.nextElementSibling},getHeaderDiv:function(){return document.querySelector("main .sticky")},getLastPrompt:function(){return x.getChatData("active","msg","user","latest")},getLastResponse:function(){return x.getChatData("active","msg","chatgpt","latest")},getNewChatButton:function(){for(const e of document.querySelectorAll("nav button svg"))if(e.querySelector('path[d*="M15.673 3.913a3.121"], path[d*="M3.07 10.876C3.623"]'))return e.parentNode},getNewChatLink:function(){return document.querySelector('nav a[href="/"]')},getRegenerateButton:function(){for(const e of document.querySelectorAll("main svg"))if(e.querySelector('path[d*="M3.07 10.876C3.623"]'))return e.parentNode},getResponse:function(){return x.response.get(...arguments)},getResponseFromAPI:function(e,t){return x.response.getFromAPI(e,t)},getResponseFromDOM:function(e){return x.response.getFromDOM(e)},getScrollToBottomButton:function(){return document.querySelector('button[class*="cursor"][class*="bottom"]')},getSendButton:function(){return document.querySelector('[data-testid="send-button"]')||document.querySelector('path[d*="M15.192 8.906a1.143"]')?.parentNode.parentNode},getStopGeneratingButton:function(){for(const e of document.querySelectorAll("form button svg"))if(e.querySelector('path[d*="2 0 0 1 2"], rect'))return e.parentNode},getUserLanguage:function(){return navigator.languages[0]||navigator.language||navigator.browserLanguage||navigator.systemLanguage||navigator.userLanguage||""},hideFooter:function(){x.getFooterDiv().style.display="none"},hideHeader:function(){x.getHeaderDiv().style.display="none"},history:{isLoaded:function(){return new Promise(t=>{!function e(){document.querySelector("nav")?t(!0):setTimeout(e,200)}()})}},instructions:{add:function(o,r){var e;return o?"string"!=typeof o?console.error("Instruction must be a string"):(e=["user","chatgpt"],r?"string"!=typeof r?console.error("Target must be a string"):(r=r.toLowerCase(),e.includes(r)?(o=`
11
+ `}else{s=await(await fetch(await chatgpt.shareChat(e))).text(),i=(new DOMParser).parseFromString(s,"text/html");r=`${i.querySelector("title").textContent||"ChatGPT conversation"}.html`,i.querySelectorAll('link[rel="stylesheet"]').forEach(e=>{var t=e.getAttribute("href");t?.startsWith("/")&&e.setAttribute("href","https://chat.openai.com"+t)}),a=(new XMLSerializer).serializeToString(i)}if(console.info(`Exporting transcript as ${t.toUpperCase()}...`),"pdf"==t){a=a.replace(/<svg.*?<\/svg>/g,e=>`<img src="${"data:image/svg+xml,"+encodeURIComponent(e)}">`);let e=window.open("","","toolbar=0, location=0, menubar=0, height=600, width=800");e.document.write(a),setTimeout(()=>{e.print({toPDF:!0})},100)}else{"md"==t&&(c=/<.*(?:<h1(.|\n)*?href=".*?continue[^"]*".*?\/a>.*?)<[^/]/.exec(a)[1],a=c||a,r=r.replace(".html",".md"));o=new Blob([a],{type:"text/"+("html"==t?"html":"md"==t?"markdown":"plain")}),n=document.createElement("a"),e=URL.createObjectURL(o);n.href=e,n.download=r,document.body.append(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(e)}},extractCode(){chatgpt.code.extract()},focusChatbar(){chatgpt.getChatBox()?.focus()},generateRandomIP(){var e=Array.from({length:4},()=>Math.floor(256*chatgpt.randomFloat())).join(".");return console.info("IP generated: "+e),e},get(e,t=""){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid arguments. Both arguments must be strings.");if(!cjsTargetTypes.includes(e.toLowerCase()))throw new Error("Invalid targetType: "+e+". Valid values are: "+JSON.stringify(cjsTargetTypes));var r,o=[],a=new RegExp("^get(.*)"+e+"$","i");for(r in chatgpt)"function"==typeof chatgpt[r]&&a.test(r)&&o.push(r.replace(a,"$1").toLowerCase());if(!o.includes(t.toLowerCase()))throw new Error("Invalid targetName: "+t+". "+(0<o.length?"Valid values are: "+JSON.stringify(o):"targetType "+e.toLowerCase()+" does not require additional options."));let n=("get"+t+e).toLowerCase();return this[Object.keys(this).find(e=>e.toLowerCase()==n)]()},getAccessToken(){return new Promise((e,t)=>{if(0<Object.keys(chatgpt.openAIaccessToken).length&&0<=Date.parse(chatgpt.openAIaccessToken.expireDate)-Date.parse(new Date))return e(chatgpt.openAIaccessToken.token);let r=new XMLHttpRequest;r.open("GET",chatgpt.endpoints.openAI.session,!0),r.setRequestHeader("Content-Type","application/json"),r.onload=()=>200!==r.status?t("🤖 chatgpt.js >> Request failed. Cannot retrieve access token."):(console.info("Token expiration: "+new Date(JSON.parse(r.responseText).expires).toLocaleString().replace(","," at")),chatgpt.openAIaccessToken={token:JSON.parse(r.responseText).accessToken,expireDate:JSON.parse(r.responseText).expires},e(chatgpt.openAIaccessToken.token)),r.send()})},getAccountDetails(...s){var e,t=["email","id","image","name","picture"];for(e of s=arguments[0]?Array.isArray(arguments[0])?arguments[0]:Array.from(arguments):t)if(!t.includes(e))return console.error("Invalid detail arg '"+e+"' supplied. Valid details are:\n ["+t+"]");return new Promise((o,a)=>{let n=new XMLHttpRequest;n.open("GET",chatgpt.endpoints.openAI.session,!0),n.setRequestHeader("Content-Type","application/json"),n.onload=()=>{if(200!==n.status)return a("🤖 chatgpt.js >> Request failed. Cannot retrieve account details.");var e,t=JSON.parse(n.responseText).user,r={};for(e of s)r[e]=t[e];return o(r)},n.send()})},getChatBox(){return document.getElementById("prompt-textarea")},getChatData(d=1,o="all",p="all",h="all"){var e,t=["all","id","title","create_time","update_time","msg"],r=["all","both","user","chatgpt"];d=d?Number.isInteger(d)||/^\d+$/.test(d)?0===parseInt(d,10)?0:parseInt(d,10)-1:d:"active",o=["all",""].includes(o)?t.filter(e=>/^(?!all$|msg$).*/.test(e)):Array.isArray(o)?o:[o],p=p?r.includes(p)?p:"invalid":"all",h=Number.isInteger(h)||/^\d+$/.test(h)?0===parseInt(h,10)?0:parseInt(h,10)-1:["all","latest"].includes(h.toLowerCase())?h.toLowerCase():h?"invalid":"all";for(e of o)if(!t.includes(e))return console.error("Invalid detail arg '"+e+"' passed. Valid details are:\n ["+t+"]");if("invalid"==p)return console.error("Invalid sender arg passed. Valid senders are:\n ["+r+"]");if("invalid"==h)return console.error("Invalid msgToGet arg passed. Valid msg's to get are:\n [ 'all' | 'latest' | index of msg to get ]");let a=(e,c)=>{let l=/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/;return new Promise((t,s)=>{let i=new XMLHttpRequest;i.open("GET",chatgpt.endpoints.openAI.chats,!0),i.setRequestHeader("Content-Type","application/json"),i.setRequestHeader("Authorization","Bearer "+e),i.onload=()=>{if(200!==i.status)return s("🤖 chatgpt.js >> Request failed. Cannot retrieve chat details.");var r=JSON.parse(i.responseText).items;if(r.length<=0)return s("🤖 chatgpt.js >> Chat list is empty.");var o={};if(Number.isInteger(d)||"latest"==d||"active"==d&&!new RegExp("/"+l.source+"$").test(window.location.href)){if((d=Number.isInteger(d)?d:0)>r.length)return s("🤖 chatgpt.js >> Chat with index "+(d+1)+" is out of bounds. Only "+r.length+" chats exist!");for(var e of c)o[e]=r[d][e]}else{var a,n="active"==d||new RegExp("^"+l.source+"$").test(d)?"id":"title";"active"==d&&(d=l.exec(window.location.href)[0]);let e,t;for(e=0;e<r.length;e++)if(r[e][n]==d){t=!0;break}if(!t)return s("🤖 chatgpt.js >> No chat with "+n+" = "+d+" found.");for(a of c)o[a]=r[e][a]}return t(o)},i.send()})};return new Promise(r=>chatgpt.getAccessToken().then(e=>{return r(o.includes("msg")?(t=e,new Promise((d,g)=>{let u=new XMLHttpRequest;a(t,["id"]).then(e=>{u.open("GET",chatgpt.endpoints.openAI.chat+"/"+e.id,!0),u.setRequestHeader("Content-Type","application/json"),u.setRequestHeader("Authorization","Bearer "+t),u.onload=()=>{if(200!==u.status)return g("🤖 chatgpt.js >> Request failed. Cannot retrieve chat messages.");var e,t,r=JSON.parse(u.responseText).mapping,o=[],a=[],n=[];for(e in r)null!=r[e].message&&"user"==r[e].message.author.role&&o.push({id:r[e].id,msg:r[e].message});if(o.sort((e,t)=>e.msg.create_time-t.msg.create_time),parseInt(h,10)+1>o.length)return g("🤖 chatgpt.js >> Message/response with index "+(h+1)+" is out of bounds. Only "+o.length+" messages/responses exist!");for(t of o){let e=[];for(var s in r)null!=r[s].message&&"assistant"==r[s].message.author.role&&r[s].parent==t.id&&e.push(r[s].message);e.sort((e,t)=>e.create_time-t.create_time),e=1===(e=e.map(e=>{switch(e.content.content_type){case"code":return e.content.text;case"text":return e.content.parts[0];default:return}})).length?e[0]:e,a.push(e)}if("user"==p)for(var i in o)n.push(o[i].msg.content.parts[0]);else if("chatgpt"==p)for(var c of a)n.push("latest"==h?a[a.length-1]:c);else{let e=0;for(var l in o)n.push({user:o[l].msg.content.parts[0],chatgpt:"latest"==h?a[e][a[e].length-1]:a[e]}),e++}return d("all"==h?n:"latest"==h?n[n.length-1]:n[h])},u.send()})})):a(e,o));var t}))},getChatInput(){return chatgpt.getChatBox().value},getContinueGeneratingButton(){for(var e of document.querySelectorAll("form button svg"))if(e.querySelector('path[d*="M4.472 2.5a1"]'))return e.parentNode.parentNode},getFooterDiv(){return document.querySelector("main form")?.parentNode.parentNode.nextElementSibling},getHeaderDiv(){return document.querySelector("main .sticky")},getLastPrompt(){return chatgpt.getChatData("active","msg","user","latest")},getLastResponse(){return chatgpt.getChatData("active","msg","chatgpt","latest")},getNewChatButton(){for(var e of document.querySelectorAll("nav button svg"))if(e.querySelector('path[d^="M15.6729"], path[d^="M3.06957"]'))return e.parentNode},getNewChatLink(){return document.querySelector('nav a[href="/"]')},getRegenerateButton(){for(var e of document.querySelectorAll("main svg"))if(e.querySelector('path[d*="M3.07 10.876C3.623"]'))return e.parentNode},getResponse(){return chatgpt.response.get(...arguments)},getResponseFromAPI(e,t){return chatgpt.response.getFromAPI(e,t)},getResponseFromDOM(e){return chatgpt.response.getFromDOM(e)},getScrollToBottomButton(){return document.querySelector('button[class*="cursor"][class*="bottom"]')},getSendButton(){return document.querySelector('[data-testid="send-button"]')||document.querySelector('path[d*="M15.192 8.906a1.143"]')?.parentNode.parentNode},getStopGeneratingButton(){for(var e of document.querySelectorAll("form button svg"))if(e.querySelector('path[d*="2 0 0 1 2"], rect'))return e.parentNode},getUserLanguage(){return navigator.languages[0]||navigator.language||navigator.browserLanguage||navigator.systemLanguage||navigator.userLanguage||""},hideFooter(){chatgpt.getFooterDiv().style.display="none"},hideHeader(){chatgpt.getHeaderDiv().style.display="none"},history:{isLoaded(){return new Promise(t=>{!function e(){document.querySelector("nav")?t(!0):setTimeout(e,200)}()})}},instructions:{add(o,a){var e;return o?"string"!=typeof o?console.error("Instruction must be a string"):(e=["user","chatgpt"],a?"string"!=typeof a?console.error("Target must be a string"):(a=a.toLowerCase(),e.includes(a)?(o=`
6
12
 
7
- `+o,new Promise(n=>{x.getAccessToken().then(async e=>{var t=await this.fetchData();return"user"==r?t.about_user_message+=o:"chatgpt"==r&&(t.about_model_message+=o),await this.sendRequest("POST",e,t),n()})})):console.error(`Invalid target ${r}. Valid targets are [${e}]`)):console.error("Please provide a valid target!")):console.error("Please provide an instruction")},clear:function(o){var e=["user","chatgpt"];return o?"string"!=typeof o?console.error("Target must be a string"):(o=o.toLowerCase(),e.includes(o)?new Promise(n=>{x.getAccessToken().then(async e=>{var t=await this.fetchData();return"user"==o?t.about_user_message="":"chatgpt"==o&&(t.about_model_message=""),await this.sendRequest("POST",e,t),n()})}):console.error(`Invalid target ${o}. Valid targets are [${e}]`)):console.error("Please provide a valid target!")},fetchData:function(){return new Promise(t=>{x.getAccessToken().then(async e=>t(await this.sendRequest("GET",e)))})},sendRequest:function(r,e,s){for(let e=0;e<arguments.length-1;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string`);var t=["POST","GET"];return(r=(r||"").trim().toUpperCase())&&t.includes(r)?e?s&&"object"!=typeof s?console.error(`Invalid body data type. Got ${typeof s}, expected object`):new Promise((t,n)=>{const o=new XMLHttpRequest;o.open(r,x.endpoints.openAI.instructions,!0),o.setRequestHeader("Accept-Language","en-US"),o.setRequestHeader("Authorization","Bearer "+e),"POST"==r&&o.setRequestHeader("Content-Type","application/json"),o.onload=()=>{var e=JSON.parse(o.responseText);return 422===o.status?n("🤖 chatgpt.js >> Character limit exceeded. Custom instructions can have a maximum length of 1500 characters."):403===o.status&&"content_policy"==e.detail.reason?n("🤖 chatgpt.js >> "+e.detail.description):200!==o.status?n("🤖 chatgpt.js >> Request failed. Cannot contact custom instructions endpoint."):(console.info("Custom instructions successfully contacted with method "+r),t(e||{}))},o.send(JSON.stringify(s)||"")}):console.error("Please provide a valid access token!"):console.error("Valid methods are "+t)},turnOff:function(){return new Promise(n=>{x.getAccessToken().then(async e=>{var t=await this.fetchData();return t.enabled=!1,await this.sendRequest("POST",e,t),n()})})},turnOn:function(){return new Promise(n=>{x.getAccessToken().then(async e=>{var t=await this.fetchData();return t.enabled=!0,await this.sendRequest("POST",e,t),n()})})},toggle:function(){return new Promise(t=>{this.fetchData().then(async e=>(await(e.enabled?this.turnOff():this.turnOn()),t()))})}},isDarkMode:function(){return document.documentElement.classList.toString().includes("dark")},isFullScreen:function(){return x.browser.isFullScreen()},isIdle:function(){return new Promise(t=>{!function e(){x.getRegenerateButton()?t(!0):setTimeout(e,200)}()})},isLoaded:function(){return new Promise(t=>{!function e(){x.getNewChatButton()?t(!0):setTimeout(e,200)}()})},isLightMode:function(){return document.documentElement.classList.toString().includes("light")},logout:function(){window.location.href="https://chat.openai.com/auth/logout"},menu:{elements:[],addedEvent:!1,append:function(e,t={}){var n=["button","dropdown"];if(!e||"string"!=typeof e)return console.error("🤖 chatgpt.js >> Please supply a valid string element name!");if(e=e.toLowerCase(),!n.includes(e))return console.error(`🤖 chatgpt.js >> Invalid element! Valid elements are [${n}]`);const o=document.createElement("dropdown"==e?"select":"button"==e?"a":e);if(o.id=Math.floor(1e6*x.randomFloat())+Date.now(),"button"==e){o.textContent=t?.label&&"string"==typeof t.label?t.label:"chatgpt.js button";n=document.createElement("img");n.src=t?.icon&&"string"==typeof t.icon?t.icon:x.endpoints.assets+"/starters/chrome/extension/icons/icon128.png",n.width=18,o.insertBefore(n,o.firstChild),o.onclick=t?.onclick&&"function"==typeof t.onclick?t.onclick:function(){}}else if("dropdown"==e){if(t?.items&&Array.isArray(t.items)&&t.items.length||(t.items=[{text:"🤖 chatgpt.js option",value:"chatgpt.js option value"}]),!t.items.every(e=>"object"==typeof e))return console.error("'items' must be an array of objects!");o.style="background-color: #000; width: 100%; border: none;",t.items.forEach(e=>{var t=document.createElement("option");t.textContent=e?.text,t.value=e?.value,o.add(t)})}const r=()=>{var e,t=document.querySelectorAll('a[role="menuitem"]');let n;for(e of t)if("Settings"==e.textContent){n=e.classList;break}const o=t[0].parentNode;x.menu.elements.forEach(e=>{if(e.setAttribute("class",n),!o.contains(e))try{o.insertBefore(e,o.firstChild)}catch(e){console.error(e)}})};this.elements.push(o);n=document.querySelector('nav button[id*="headless"]');return this.addedEvent||(n.addEventListener("click",()=>{setTimeout(r,25)}),this.addedEvent=!0),o.id},close:function(){try{document.querySelector('nav [id*="menu-button"][aria-expanded="true"]').click()}catch(e){console.error(e.message)}},open:function(){try{document.querySelector('nav [id*="menu-button"][aria-expanded="false"]').click()}catch(e){console.error(e.message)}}},minify:function(){x.code.minify()},notify:async function(e,t,n,o){n=n?+n:1.75;const r=document.createElement("div");r.id=Math.floor(1e6*x.randomFloat())+Date.now(),r.classList.add("chatgpt-notif"),r.innerText=e,document.body.append(r);var e=document.createElement("div"),s=(e.title="Dismiss",e.classList.add("notif-close-btn"),document.createElementNS("http://www.w3.org/2000/svg","svg")),a=(s.setAttribute("height","8px"),s.setAttribute("viewBox","0 0 14 14"),s.setAttribute("fill","none"),s.style.height=s.style.width="8px",document.createElementNS("http://www.w3.org/2000/svg","path"));a.setAttribute("fill-rule","evenodd"),a.setAttribute("clip-rule","evenodd"),a.setAttribute("fill","white"),a.setAttribute("d","M13.7071 1.70711C14.0976 1.31658 14.0976 0.683417 13.7071 0.292893C13.3166 -0.0976312 12.6834 -0.0976312 12.2929 0.292893L7 5.58579L1.70711 0.292893C1.31658 -0.0976312 0.683417 -0.0976312 0.292893 0.292893C-0.0976312 0.683417 -0.0976312 1.31658 0.292893 1.70711L5.58579 7L0.292893 12.2929C-0.0976312 12.6834 -0.0976312 13.3166 0.292893 13.7071C0.683417 14.0976 1.31658 14.0976 1.70711 13.7071L7 8.41421L12.2929 13.7071C12.6834 14.0976 13.3166 14.0976 13.7071 13.7071C14.0976 13.3166 14.0976 12.6834 13.7071 12.2929L8.41421 7L13.7071 1.70711Z"),s.append(a),e.append(s),r.append(e),r.isTop=!t||!/low|bottom/i.test(t),r.isRight=!t||!/left/i.test(t),r.quadrant=(r.isTop?"top":"bottom")+(r.isRight?"Right":"Left");let i=document.querySelector("#chatgpt-notif-style"),c=((!i||parseInt(i.getAttribute("last-updated"),10)<20231110)&&(i||((i=document.createElement("style")).id="chatgpt-notif-style",i.setAttribute("last-updated",20231110..toString()),document.head.append(i)),i.innerText=".chatgpt-notif {background-color: black ; padding: 10px 13px 10px 18px ; border-radius: 11px ; border: 1px solid #f5f5f7 ;opacity: 0 ; position: fixed ; z-index: 9999 ; font-size: 1.8rem ; color: white ;-webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ;"+`transform: translateX(${r.isRight?"":"-"}35px) ;`+(o?"box-shadow: -8px 13px 25px 0 "+(/\b(shadow|on)\b/gi.test(o)?"gray":o):"")+"}.notif-close-btn { cursor: pointer ; float: right ; position: relative ; right: -4px ; margin-left: -3px ;display: grid }@keyframes notif-zoom-fade-out { 0% { opacity: 1 ; transform: scale(1) }15% { opacity: 0.35 ; transform: rotateX(-27deg) scale(1.05) }45% { opacity: 0.05 ; transform: rotateX(-81deg) }100% { opacity: 0 ; transform: rotateX(-180deg) scale(1.15) }}"),JSON.parse(localStorage.notifyProps));c.queue[r.quadrant].push(r.id),localStorage.notifyProps=JSON.stringify(c),r.style.top=r.isTop?23..toString()+"px":"",r.style.bottom=r.isTop?"":23..toString()+"px",r.style.right=r.isRight?27..toString()+"px":"",r.style.left=r.isRight?"":27..toString()+"px";a=c.queue[r.quadrant];if(1<a.length)try{for(const p of a.slice(0,-1)){var l=document.getElementById(p),u=l.style.top?"top":"bottom",d=+/\d+/.exec(l.style[u])[0]+5+l.getBoundingClientRect().height;l.style[u]=d+"px"}}catch(e){}setTimeout(()=>{r.style.opacity=x.isDarkMode()?.8:.67,r.style.transform="translateX(0)",r.style.transition="transform 0.15s ease, opacity 0.15s ease"},10);e=()=>{r.style.animation="notif-zoom-fade-out 0.35s ease-out",clearTimeout(g)};const g=setTimeout(e,1e3*(n<.35?0:n-.35));s.addEventListener("click",e,{once:!0}),r.addEventListener("animationend",()=>{r.remove(),(c=JSON.parse(localStorage.notifyProps)).queue[r.quadrant].shift(),localStorage.notifyProps=JSON.stringify(c)},{once:!0})},obfuscate:function(){x.code.obfuscate()},printAllFunctions:function(){const t={cmdPrompt:["#ff00ff","#00ff00"],objName:["#0611e9","#f9ee16"],methodName:["#005aff","#ffa500"],entryType:["#467e06","#b981f9"],srcMethod:["#ff0000","#00ffff"]};Object.keys(t).forEach(e=>{t[e][1]=t[e][1]||"#"+(16777215^Number("0x1"+t[e][0].replace(/^#/,""))).toString(16).substring(1).toUpperCase()});var e=[];for(const c in this)if("function"==typeof this[c]){var n=!Object.keys(this).find(e=>Object.keys(this[e]).includes(this[c].name));e.push([n?"chatgpt":"other",c])}else if("object"==typeof this[c])for(const l in this[c])"function"==typeof this[c][l]&&e.push([c,l]);e.sort((e,t)=>e[0].localeCompare(t[0])||e[1].localeCompare(t[1]));var o=window.matchMedia("(prefers-color-scheme: dark)").matches,r="font-family: monospace ; font-size: larger ; ";console.log("\n%c🤖 chatgpt.js methods\n","font-family: sans-serif ; font-size: xxx-large ; font-weight: bold");for(const u of e){var s=/chatgpt|other/.test(u[0]),a="chatgpt"==u[0]?this[u[1]].name:"other"!==u[0]?u[0]+"."+u[1]:Object.keys(this).find(e=>Object.keys(this[e]).includes(this[u[1]].name))+"."+this[u[1]].name,i="AsyncFunction"==this[u[1]]?.constructor.name;console.log("%c>> %c"+(s?"":u[0]+".%c")+u[1]+" - https://chatgptjs.org/userguide/"+/(?:.*\.)?(.*)/.exec(a)[1].toLowerCase()+(i?"-async":"")+"\n%c[%c"+("chatgpt"==u[0]&&u[1]==this[u[1]].name||!s?"Function":"Alias of")+"%c: %c"+a+"%c]",r+"font-weight: bold ; color:"+t.cmdPrompt[+o],r+"font-weight: bold ;color:"+t[s?"methodName":"objName"][+o],r+"font-weight: "+(s?"initial":"bold")+";color:"+(s?"initial":t.methodName[+o]),r+"font-weight: "+(s?"bold":"initial")+";color:"+(s?t.entryType[+o]:"initial"),r+"font-weight: "+(s?"initial":"bold")+";color:"+(s?"initial":t.entryType[+o]),r+(s?"font-style: italic":"font-weight: initial")+";color:"+(s?t.srcMethod[+o]:"initial"),r+(s?"font-weight: initial":"font-style: italic")+";color:"+(s?"initial":t.srcMethod[+o]),s?"":r+"color: initial ; font-weight: initial")}},randomFloat:function(){return(window.crypto||window.msCrypto)?.getRandomValues(new Uint32Array(1))[0]/4294967295||Math.random()},refactor:function(){x.code.refactor()},regenerate:function(){x.response.regenerate()},renderHTML:function(e){var t=/<([a-z\d]+)\b([^>]*)>([\s\S]*?)<\/\1>/g,n=/(\S+)=['"]?((?:.(?!['"]?\s+\S+=|[>']))+.)['"]?/g,o=e.childNodes;x.renderHTML.preWrapSet||(e.style.whiteSpace="pre-wrap",x.renderHTML.preWrapSet=!0,setTimeout(()=>{x.renderHTML.preWrapSet=!1},100));for(const i of o)if(i.nodeType==Node.TEXT_NODE){var r=i.nodeValue,s=Array.from(r.matchAll(t));if(0<s.length){const c=s[0],[l,u,d,g]=c.slice(0,4),p=document.createElement(u);p.textContent=g;Array.from(d.matchAll(n)).forEach(e=>{var t=e[1],e=e[2].replace(/['"]/g,"");p.setAttribute(t,e)});var s=x.renderHTML(p),a=document.createTextNode(r.substring(0,c.index)),r=document.createTextNode(r.substring(c.index+l.length));e.replaceChild(a,i),e.insertBefore(s,a.nextSibling),e.insertBefore(r,s.nextSibling)}}else i.nodeType==Node.ELEMENT_NODE&&x.renderHTML(i);return e},resend:async function(){x.send(await x.getChatData("latest","msg","user","latest"))},response:{continue:function(){try{x.getContinueBtn().click()}catch(e){console.error(e.message)}},get:function(){return(window.location.href.startsWith("https://chatgpt.com/c/")?this.getFromDOM:this.getFromAPI).apply(null,arguments)},getFromAPI:function(e,t){return e=e||"latest",t=t||"latest",x.getChatData(e,"msg","chatgpt",t)},getFromDOM:function(e){var t=document.querySelectorAll('div[data-testid*="conversation-turn"]:nth-child(odd)'),n=e.toString().toLowerCase();let o="";return o=t.length?(o=(/last|final/.test(n)?t[t.length-1]:t[(Number.isInteger(e)?e:/^\d+/.test(n)?/^\d+/.exec(n)[0]:(/^(?:1|one|fir)(?:st)?$/.test(n)?1:/^(?:2|tw(?:o|en|el(?:ve|f))|seco)(?:nd|t[yi])?(?:e?th)?$/.test(n)?2:/^(?:3|th(?:ree|ir?))(?:rd|teen|t[yi])?(?:e?th)?$/.test(n)?3:/^(?:4|fou?r)(?:teen|t[yi])?(?:e?th)?$/.test(n)?4:/^(?:5|fi(?:ve|f))(?:teen|t[yi])?(?:e?th)?$/.test(n)?5:/^(?:6|six)(?:teen|t[yi])?(?:e?th)?$/.test(n)?6:/^(?:7|seven)(?:teen|t[yi])?(?:e?th)?$/.test(n)?7:/^(?:8|eight?)(?:teen|t[yi])?(?:e?th)?$/.test(n)?8:/^(?:9|nine?)(?:teen|t[yi])?(?:e?th)?$/.test(n)?9:/^(?:10|ten)(?:th)?$/.test(n)?10:1)*(/(ty|ieth)$/.test(n)?10:1)+(/teen(th)?$/.test(n)?10:0))-1]).textContent).replace(/^ChatGPT(?:ChatGPT)?/,""):o},getLast:function(){return x.getChatData("active","msg","chatgpt","latest")},regenerate:function(){try{x.getRegenerateBtn().click()}catch(e){console.error(e.message)}},stopGenerating:function(){try{x.getStopBtn().click()}catch(e){console.error(e.message)}}},reviewCode:function(){x.code.review()},scrollToBottom:function(){try{x.getScrollBtn().click()}catch(e){console.error(e.message)}},send:function(e,t=""){for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string!`);const n=document.querySelector("form textarea"),o=x.getSendButton();n.value=e,n.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(function e(){o?.hasAttribute("disabled")?setTimeout(e,25):"click"==t.toLowerCase()||x.browser.isMobile()?o.click():n.dispatchEvent(new KeyboardEvent("keydown",{keyCode:13,bubbles:!0}))},25)},sendInNewChat:function(e){if("string"!=typeof e)return console.error("Message must be a string!");for(const t of document.querySelectorAll("nav a"))if(/(new|clear) chat/i.test(t.text)){t.click();break}setTimeout(()=>{x.send(e)},500)},settings:{scheme:{isDark:function(){return document.documentElement.classList.contains("dark")},isLight:function(){return document.documentElement.classList.contains("light")},set:function(e){var t=["dark","light","system"];if(!e)return console.error("Please specify a scheme value!");if(!t.includes(e))return console.error(`Invalid scheme value. Valid values are [${t}]`);let n=e;"system"==e&&(n=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),localStorage.setItem("theme",e),console.info(`Scheme set to ${e.toUpperCase()}.`),document.documentElement.classList.contains(n)||this.toggle()},toggle:function(){var[e,t]=this.isDark()?["dark","light"]:["light","dark"];document.documentElement.classList.replace(e,t),document.documentElement.style.colorScheme=t,localStorage.setItem("theme",t)}}},sentiment:async function(e,t){for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return x.send("What is the sentiment of the following text"+(t?` towards the entity ${t},`:"")+" from strongly negative to strongly positive?\n\n"+e),console.info("Analyzing sentiment..."),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")},setScheme:function(e){x.settings.scheme.set(e)},shareChat:function(a,i="clipboard"){var e=["alert","notify","notification","clipboard","copy"];if(!e.includes(i))return console.error("Invalid method '"+i+"' passed. Valid methods are ["+e+"].");return new Promise(n=>{x.getAccessToken().then(t=>{var r;r=t,new Promise((t,n)=>{const o=new XMLHttpRequest;x.getChatData(a).then(e=>{o.open("GET",x.endpoints.openAI.chat+"/"+e.id,!0),o.setRequestHeader("Content-Type","application/json"),o.setRequestHeader("Authorization","Bearer "+r),o.onload=()=>200!==o.status?n("🤖 chatgpt.js >> Request failed. Cannot retrieve chat node."):t(JSON.parse(o.responseText).current_node),o.send()})}).then(e=>{var r,s;r=t,s=e,new Promise((t,n)=>{const o=new XMLHttpRequest;x.getChatData(a).then(e=>{o.open("POST",x.endpoints.openAI.share_create,!0),o.setRequestHeader("Content-Type","application/json"),o.setRequestHeader("Authorization","Bearer "+r),o.onload=()=>200!==o.status?n("🤖 chatgpt.js >> Request failed. Cannot initialize share chat."):t(JSON.parse(o.responseText)),o.send(JSON.stringify({current_node_id:s,conversation_id:e.id,is_anonymous:!0}))})}).then(e=>{var o,r;o=t,r=e,new Promise((e,t)=>{const n=new XMLHttpRequest;n.open("PATCH",x.endpoints.openAI.share+"/"+r.share_id,!0),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("Authorization","Bearer "+o),n.onload=()=>200!==n.status?t("🤖 chatgpt.js >> Request failed. Cannot share chat."):(console.info(`Chat shared at '${r.share_url}'`),e()),n.send(JSON.stringify({share_id:r.share_id,highlighted_message_id:r.highlighted_message_id,title:r.title,is_public:!0,is_visible:r.is_visible,is_anonymous:r.is_anonymous}))}).then(()=>{["copy","clipboard"].includes(i)?navigator.clipboard.writeText(e.share_url):x.alert("🚀 Share link created!",'"'+e.title+'" is available at: <a target="blank" rel="noopener" href="'+e.share_url+'" >'+e.share_url+"</a>",[function(){window.open(e.share_url,"_blank","noopener")},function(){navigator.clipboard.writeText(e.share_url)}]),n(e.share_url)})})})})})},showFooter:function(){x.getFooterDiv().style.display="revert"},showHeader:function(){x.getHeaderDiv().style.display="flex"},sidebar:{elements:[],observer:{},activateObserver:function(){if(this.observer instanceof MutationObserver)try{this.observer.disconnect()}catch(e){}if(!this.elements.length)return console.error("🤖 chatgpt.js >> No elements to append!");let t;for(var e of document.querySelectorAll("nav a"))if(/.*chat/.exec(e.text)[0]){t=e.classList,e.parentNode.style.margin="2px 0";break}this.elements.forEach(e=>{e.setAttribute("class",t),e.style.maxHeight=e.style.minHeight="44px",e.style.margin="2px 0"});const n=document.querySelector("nav");this.observer=new MutationObserver(e=>{e.forEach(e=>{("childList"==e.type&&e.addedNodes.length||"attributes"==e.type&&"data-chatgptjs"==e.attributeName)&&this.elements.forEach(e=>{if(!n.contains(e))try{n.insertBefore(e,n.querySelector("a").parentNode)}catch(e){console.error(e)}})})}),this.observer.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0})},append:function(e,t={}){var n=["button","dropdown"];if(!e||"string"!=typeof e)return console.error("🤖 chatgpt.js >> Please supply a valid string element name!");if(e=e.toLowerCase(),!n.includes(e))return console.error(`🤖 chatgpt.js >> Invalid element! Valid elements are [${n}]`);const o=document.createElement("dropdown"==e?"select":e);if(o.id=Math.floor(1e6*x.randomFloat())+Date.now(),"button"==e){o.textContent=t?.label&&"string"==typeof t.label?t.label:"chatgpt.js button";n=document.createElement("img");n.src=t?.icon&&"string"==typeof t.icon?t.icon:x.endpoints.assets+"/starters/chrome/extension/icons/icon128.png",n.width=18,o.insertBefore(n,o.firstChild),o.onclick=t?.onclick&&"function"==typeof t.onclick?t.onclick:function(){}}else if("dropdown"==e){if(t?.items&&Array.isArray(t.items)&&t.items.length||(t.items=[{text:"🤖 chatgpt.js option",value:"chatgpt.js option value"}]),!t.items.every(e=>"object"==typeof e))return console.error("'items' must be an array of objects!");t.items.forEach(e=>{var t=document.createElement("option");t.textContent=e?.text,t.value=e?.value,o.add(t)})}return"dropdown"==e&&(o.style.backgroundColor="var(--gray-900, rgb(32, 33, 35))"),this.elements.push(o),this.activateObserver(),document.body.setAttribute("data-chatgptjs","observer-trigger"),o.id},hide:function(){this.isOn()?this.toggle():console.info("Sidebar already hidden!")},show:function(){this.isOff()?this.toggle():console.info("Sidebar already shown!")},isOff:function(){return!this.isOn()},isOn:function(){var e=document.querySelector("#__next > div > div");return x.browser.isMobile()?"hidden"==document.documentElement.style.overflow:"hidden"!=e.style.visibility&&"0px"!=e.style.width},toggle:function(){var e=x.browser.isMobile(),t=e?()=>!0:e=>0<e.querySelectorAll('svg path[d*="M8.857 3h6.286c1.084"]').length;for(const n of document.querySelectorAll(e?"#__next button":"nav button"))if(t(n))return void n.click()},isLoaded:async function(){return await x.isLoaded(),Promise.race([new Promise(t=>{!function e(){x.getNewChatLink()?t(!0):setTimeout(e,200)}()}),new Promise(e=>setTimeout(e,5e3))])}},startNewChat:function(){try{x.getNewChatBtn().click()}catch(e){console.error(e.message)}},stop:function(){x.response.stopGenerating()},suggest:async function(e,t){if(!e)return console.error("ideaType (1st argument) not supplied(e.g. 'gifts', 'names', 'recipes', etc.)");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return x.send("Suggest some names. "+(t||"")),console.info(`Creating ${e}...`),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")},speak:function(e,t={}){var n,{voice:o=2,pitch:r=2,speed:s=1.1}=t;if("string"!=typeof e)return console.error("Message must be a string!");for(n in t){var a=t[n];if("number"!=typeof a&&!/^\d+$/.test(a))return console.error(`Invalid ${n} index '${a}'. Must be a number!`)}try{var i=speechSynthesis.getVoices(),c=new SpeechSynthesisUtterance;c.text=e,c.voice=i[o],c.pitch=r,c.rate=s,speechSynthesis.speak(c)}catch(e){console.error(e)}},summarize:async function(e){return e?"string"!=typeof e?console.error("Text argument must be a string!"):(x.send("Summarize the following text:\n\n"+e),console.info("Summarizing text..."),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")):console.error("Text (1st) argument not supplied. Pass some text!")},toggleScheme:function(){x.settings.scheme.toggle()},translate:async function(e,t){if(!e)return console.error("Text (1st) argument not supplied. Pass some text!");if(!t)return console.error("outputLang (2nd) argument not supplied. Pass a language!");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string!`);return x.send("Translate the following text to "+t+". Only reply with the translation.\n\n"+e),console.info("Translating text..."),await x.isIdle(),x.getChatData("active","msg","chatgpt","latest")},unminify:function(){x.code.unminify()},uuidv4:function(){let n=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{var t=(n+window.crypto.getRandomValues(new Uint32Array(1))[0]/(Math.pow(2,32)-1)*16)%16|0;return n=Math.floor(n/16),("x"==e?t:3&t|8).toString(16)})},writeCode:function(){x.code.write()}},e=(x.scheme={...x.settings.scheme},["click","get"]),a=["button","link","div","response"];for(const l of e)x[l+"Button"]=function(n){var e=/^[.#]/.test(n)?document.querySelector(n):/send/i.test(n)?document.querySelector('form button[class*="bottom"]'):/scroll/i.test(n)?document.querySelector('button[class*="cursor"]'):function(){for(const e of document.querySelectorAll("button"))if(e.textContent.toLowerCase().includes(n.toLowerCase()))return e;for(const t of document.querySelectorAll("nav a"))if(t.textContent.toLowerCase().includes(n.toLowerCase()))return t}();if("click"!=l)return e;e.click()};const t=[["actAs","actas","act","become","persona","premadePrompt","preMadePrompt","prePrompt","preprompt","roleplay","rolePlay","rp"],["activateAutoRefresh","activateAutoRefresher","activateRefresher","activateSessionRefresher","autoRefresh","autoRefresher","autoRefreshSession","refresher","sessionRefresher"],["continue","continueChat","continueGenerating","continueResponse"],["deactivateAutoRefresh","deactivateAutoRefresher","deactivateRefresher","deactivateSessionRefresher"],["detectLanguage","getLanguage"],["executeCode","codeExecute"],["exportChat","chatExport","export"],["getFooterDiv","getFooter"],["getHeaderDiv","getHeader"],["getLastPrompt","getLastQuery","getMyLastMsg","getMyLastQuery"],["getContinueGeneratingButton","getContinueButton"],["getScrollToBottomButton","getScrollButton"],["getStopGeneratingButton","getStopButton"],["getTextarea","getTextArea","getChatbox","getChatBox"],["isFullScreen","isFullscreen","isfullscreen"],["isLoaded","isloaded"],["logOut","logout","logOff","logoff","signOut","signout","signOff","signoff"],["minify","codeMinify","minifyCode"],["new","newChat","startNewChat"],["obfuscate","codeObfuscate","obfuscateCode"],["printAllFunctions","showAllFunctions"],["refactor","codeRefactor","refactorCode"],["refreshReply","regenerate","regenerateReply"],["refreshSession","sessionRefresh"],["renderHTML","renderHtml","renderLinks","renderTags"],["reviewCode","codeReview"],["send","sendChat","sendMsg"],["sendInNewChat","sendNewChat"],["sentiment","analyzeSentiment","sentimentAnalysis"],["startNewChat","new","newChat"],["stop","stopChat","stopGenerating","stopResponse"],["suggest","suggestion","recommend"],["toggleAutoRefresh","toggleAutoRefresher","toggleRefresher","toggleSessionRefresher"],["toggleScheme","toggleMode"],["translate","translation","translator"],["unminify","unminifyCode","codeUnminify"],["writeCode","codeWrite"]],n=[["account","acct"],["activate","turnOn"],["analyze","check","evaluate","review"],["ask","send","submit"],["button","btn"],["continue","resume"],["chats","history"],["chat","conversation","convo"],["clear","delete","remove"],["data","details"],["deactivate","deActivate","turnOff"],["execute","interpret","interpreter","run"],["firefox","ff"],["generating","generation"],["minify","uglify"],["refactor","rewrite"],["regenerate","regen"],["render","parse"],["reply","response"],["sentiment","attitude","emotion","feeling","opinion","perception"],["speak","say","speech","talk","tts"],["summarize","tldr"],["unminify","beautify","prettify","prettyPrint"]],o=e=>e.map((e,t)=>0===t||"s"==e?e:e.charAt(0).toUpperCase()+e.slice(1)).join("");for(const u in x){for(const d of t)if(d.includes(u))if(d.some(e=>e.includes("."))){const g=d.find(e=>e.includes(".")).split(".")[1];for(const p of d)/^(\w+)/.exec(p)[1]!==u&&(x[p]=x[u][g])}else for(const f of d)f!==u&&(x[f]=x[u]);do{var r=!1;for(const m in x)if("function"==typeof x[m]){const h=m.split(/(?=[A-Zs])/);for(const y of h){const v=[].concat(...n.filter(e=>e.includes(y.toLowerCase())).map(e=>e.filter(e=>e!==y.toLowerCase())));for(const w of v){const b=o(h.map(e=>e==y?w:e));x[b]||(x[b]=x[m],r=!0)}}}}while(r)}const s="🤖 chatgpt.js >> ",i=console.error,c=console.info;console.error=(...e)=>{e[0].startsWith(s)?i(...e):i(s+e[0],...e.slice(1))},console.info=e=>{e.startsWith(s)?c(e):c(s+e)};try{window.chatgpt=x}catch(e){}try{module.exports=x}catch(e){}
13
+ `+o,new Promise(r=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return"user"==a?t.about_user_message+=o:"chatgpt"==a&&(t.about_model_message+=o),await this.sendRequest("POST",e,t),r()})})):console.error(`Invalid target ${a}. Valid targets are [${e}]`)):console.error("Please provide a valid target!")):console.error("Please provide an instruction")},clear(o){var e=["user","chatgpt"];return o?"string"!=typeof o?console.error("Target must be a string"):(o=o.toLowerCase(),e.includes(o)?new Promise(r=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return"user"==o?t.about_user_message="":"chatgpt"==o&&(t.about_model_message=""),await this.sendRequest("POST",e,t),r()})}):console.error(`Invalid target ${o}. Valid targets are [${e}]`)):console.error("Please provide a valid target!")},fetchData(){return new Promise(t=>{chatgpt.getAccessToken().then(async e=>t(await this.sendRequest("GET",e)))})},sendRequest(a,e,n){for(let e=0;e<arguments.length-1;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string`);var t=["POST","GET"];return(a=(a||"").trim().toUpperCase())&&t.includes(a)?e?n&&"object"!=typeof n?console.error(`Invalid body data type. Got ${typeof n}, expected object`):new Promise((t,r)=>{let o=new XMLHttpRequest;o.open(a,chatgpt.endpoints.openAI.instructions,!0),o.setRequestHeader("Accept-Language","en-US"),o.setRequestHeader("Authorization","Bearer "+e),"POST"==a&&o.setRequestHeader("Content-Type","application/json"),o.onload=()=>{var e=JSON.parse(o.responseText);return 422===o.status?r("🤖 chatgpt.js >> Character limit exceeded. Custom instructions can have a maximum length of 1500 characters."):403===o.status&&"content_policy"==e.detail.reason?r("🤖 chatgpt.js >> "+e.detail.description):200!==o.status?r("🤖 chatgpt.js >> Request failed. Cannot contact custom instructions endpoint."):(console.info("Custom instructions successfully contacted with method "+a),t(e||{}))},o.send(JSON.stringify(n)||"")}):console.error("Please provide a valid access token!"):console.error("Valid methods are "+t)},turnOff(){return new Promise(r=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return t.enabled=!1,await this.sendRequest("POST",e,t),r()})})},turnOn(){return new Promise(r=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return t.enabled=!0,await this.sendRequest("POST",e,t),r()})})},toggle(){return new Promise(t=>{this.fetchData().then(async e=>(await(e.enabled?this.turnOff():this.turnOn()),t()))})}},isDarkMode(){return document.documentElement.classList.toString().includes("dark")},isFullScreen(){return chatgpt.browser.isFullScreen()},isIdle(){return new Promise(t=>{!function e(){chatgpt.getRegenerateButton()?t(!0):setTimeout(e,200)}()})},isLoaded(){return new Promise(t=>{!function e(){chatgpt.getNewChatButton()?t(!0):setTimeout(e,200)}()})},isLightMode(){return document.documentElement.classList.toString().includes("light")},logout(){window.location.href="https://chat.openai.com/auth/logout"},menu:{elements:[],addedEvent:!1,append(e,t={}){var r=["button","dropdown"];if(!e||"string"!=typeof e)return console.error("🤖 chatgpt.js >> Please supply a valid string element name!");if(e=e.toLowerCase(),!r.includes(e))return console.error(`🤖 chatgpt.js >> Invalid element! Valid elements are [${r}]`);let o=document.createElement("dropdown"==e?"select":"button"==e?"a":e);if(o.id=Math.floor(1e6*chatgpt.randomFloat())+Date.now(),"button"==e){o.textContent=t?.label&&"string"==typeof t.label?t.label:"chatgpt.js button";r=document.createElement("img");r.src=t?.icon&&"string"==typeof t.icon?t.icon:chatgpt.endpoints.assets+"/starters/chrome/extension/icons/icon128.png",r.width=18,o.insertBefore(r,o.firstChild),o.onclick=t?.onclick&&"function"==typeof t.onclick?t.onclick:function(){}}else if("dropdown"==e){if(t?.items&&Array.isArray(t.items)&&t.items.length||(t.items=[{text:"🤖 chatgpt.js option",value:"chatgpt.js option value"}]),!t.items.every(e=>"object"==typeof e))return console.error("'items' must be an array of objects!");o.style="background-color: #000; width: 100%; border: none;",t.items.forEach(e=>{var t=document.createElement("option");t.textContent=e?.text,t.value=e?.value,o.add(t)})}let a=()=>{var e,t=document.querySelectorAll('a[role="menuitem"]');let r;for(e of t)if("Settings"==e.textContent){r=e.classList;break}let o=t[0].parentNode;chatgpt.menu.elements.forEach(e=>{if(e.setAttribute("class",r),!o.contains(e))try{o.insertBefore(e,o.firstChild)}catch(e){console.error(e)}})};this.elements.push(o);r=document.querySelector('nav button[id*="headless"]');return this.addedEvent||(r?.addEventListener("click",()=>{setTimeout(a,25)}),this.addedEvent=!0),o.id},close(){try{document.querySelector('nav [id*="menu-button"][aria-expanded="true"]').click()}catch(e){console.error(e.message)}},open(){try{document.querySelector('nav [id*="menu-button"][aria-expanded="false"]').click()}catch(e){console.error(e.message)}}},minify(){chatgpt.code.minify()},notify(e,t,r,o){r=r?+r:1.75;let a=document.createElement("div");a.id=Math.floor(1e6*chatgpt.randomFloat())+Date.now(),a.classList.add("chatgpt-notif"),a.innerText=e,document.body.append(a);var e=document.createElement("div"),n=(e.title="Dismiss",e.classList.add("notif-close-btn","no-mobile-tap-outline"),document.createElementNS("http://www.w3.org/2000/svg","svg")),s=(n.setAttribute("height","8px"),n.setAttribute("viewBox","0 0 14 14"),n.setAttribute("fill","none"),n.style.height=n.style.width="8px",document.createElementNS("http://www.w3.org/2000/svg","path"));s.setAttribute("fill-rule","evenodd"),s.setAttribute("clip-rule","evenodd"),s.setAttribute("fill","white"),s.setAttribute("d","M13.7071 1.70711C14.0976 1.31658 14.0976 0.683417 13.7071 0.292893C13.3166 -0.0976312 12.6834 -0.0976312 12.2929 0.292893L7 5.58579L1.70711 0.292893C1.31658 -0.0976312 0.683417 -0.0976312 0.292893 0.292893C-0.0976312 0.683417 -0.0976312 1.31658 0.292893 1.70711L5.58579 7L0.292893 12.2929C-0.0976312 12.6834 -0.0976312 13.3166 0.292893 13.7071C0.683417 14.0976 1.31658 14.0976 1.70711 13.7071L7 8.41421L12.2929 13.7071C12.6834 14.0976 13.3166 14.0976 13.7071 13.7071C14.0976 13.3166 14.0976 12.6834 13.7071 12.2929L8.41421 7L13.7071 1.70711Z"),n.append(s),e.append(n),a.append(e),a.isTop=!t||!/low|bottom/i.test(t),a.isRight=!t||!/left/i.test(t),a.quadrant=(a.isTop?"top":"bottom")+(a.isRight?"Right":"Left");let i=document.querySelector("#chatgpt-notif-style"),c=((!i||parseInt(i.getAttribute("last-updated"),10)<20231110)&&(i||((i=document.createElement("style")).id="chatgpt-notif-style",i.setAttribute("last-updated",20231110..toString()),document.head.append(i)),i.innerText=".chatgpt-notif {.no-mobile-tap-outline { outline: none ; -webkit-tap-highlight-color: transparent }background-color: black ; padding: 10px 13px 10px 18px ; border-radius: 11px ; border: 1px solid #f5f5f7 ;opacity: 0 ; position: fixed ; z-index: 9999 ; font-size: 1.8rem ; color: white ;-webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ;"+`transform: translateX(${a.isRight?"":"-"}35px) ;`+(o?"box-shadow: -8px 13px 25px 0 "+(/\b(shadow|on)\b/gi.test(o)?"gray":o):"")+"}.notif-close-btn { cursor: pointer ; float: right ; position: relative ; right: -4px ; margin-left: -3px ;display: grid }@keyframes notif-zoom-fade-out { 0% { opacity: 1 ; transform: scale(1) }15% { opacity: 0.35 ; transform: rotateX(-27deg) scale(1.05) }45% { opacity: 0.05 ; transform: rotateX(-81deg) }100% { opacity: 0 ; transform: rotateX(-180deg) scale(1.15) }}"),JSON.parse(localStorage.notifyProps));c.queue[a.quadrant].push(a.id),localStorage.notifyProps=JSON.stringify(c),a.style.top=a.isTop?23..toString()+"px":"",a.style.bottom=a.isTop?"":23..toString()+"px",a.style.right=a.isRight?27..toString()+"px":"",a.style.left=a.isRight?"":27..toString()+"px";s=c.queue[a.quadrant];if(1<s.length)try{for(var l of s.slice(0,-1)){var d=document.getElementById(l),g=d.style.top?"top":"bottom",u=+/\d+/.exec(d.style[g])[0]+5+d.getBoundingClientRect().height;d.style[g]=u+"px"}}catch(e){}setTimeout(()=>{a.style.opacity=chatgpt.isDarkMode()?.8:.67,a.style.transform="translateX(0)",a.style.transition="transform 0.15s ease, opacity 0.15s ease"},10);e=()=>{a.style.animation="notif-zoom-fade-out 0.35s ease-out",clearTimeout(p)};let p=setTimeout(e,1e3*(r<.35?0:r-.35));return n.onclick=e,a.onanimationend=()=>{a.remove(),(c=JSON.parse(localStorage.notifyProps)).queue[a.quadrant].shift(),localStorage.notifyProps=JSON.stringify(c)},a},obfuscate(){chatgpt.code.obfuscate()},printAllFunctions(){let r={cmdPrompt:["#ff00ff","#00ff00"],objName:["#0611e9","#f9ee16"],methodName:["#005aff","#ffa500"],entryType:["#467e06","#b981f9"],srcMethod:["#ff0000","#00ffff"]};Object.keys(r).forEach(e=>{r[e][1]=r[e][1]||"#"+(16777215^Number("0x1"+r[e][0].replace(/^#/,""))).toString(16).substring(1).toUpperCase()});var e=[];for(let t in this)if("function"==typeof this[t]){var o=!Object.keys(this).find(e=>Object.keys(this[e]).includes(this[t].name));e.push([o?"chatgpt":"other",t])}else if("object"==typeof this[t])for(var a in this[t])"function"==typeof this[t][a]&&e.push([t,a]);e.sort((e,t)=>e[0].localeCompare(t[0])||e[1].localeCompare(t[1]));var n=window.matchMedia("(prefers-color-scheme: dark)").matches,s="font-family: monospace ; font-size: larger ; ";console.log("\n%c🤖 chatgpt.js methods\n","font-family: sans-serif ; font-size: xxx-large ; font-weight: bold");for(let t of e){var i=/chatgpt|other/.test(t[0]),c="chatgpt"==t[0]?this[t[1]].name:"other"!==t[0]?t[0]+"."+t[1]:Object.keys(this).find(e=>Object.keys(this[e]).includes(this[t[1]].name))+"."+this[t[1]].name,l="AsyncFunction"==this[t[1]]?.constructor.name;console.log("%c>> %c"+(i?"":t[0]+".%c")+t[1]+" - https://chatgptjs.org/userguide/"+/(?:.*\.)?(.*)/.exec(c)[1].toLowerCase()+(l?"-async":"")+"\n%c[%c"+("chatgpt"==t[0]&&t[1]==this[t[1]].name||!i?"Function":"Alias of")+"%c: %c"+c+"%c]",s+"font-weight: bold ; color:"+r.cmdPrompt[+n],s+"font-weight: bold ;color:"+r[i?"methodName":"objName"][+n],s+"font-weight: "+(i?"initial":"bold")+";color:"+(i?"initial":r.methodName[+n]),s+"font-weight: "+(i?"bold":"initial")+";color:"+(i?r.entryType[+n]:"initial"),s+"font-weight: "+(i?"initial":"bold")+";color:"+(i?"initial":r.entryType[+n]),s+(i?"font-style: italic":"font-weight: initial")+";color:"+(i?r.srcMethod[+n]:"initial"),s+(i?"font-weight: initial":"font-style: italic")+";color:"+(i?"initial":r.srcMethod[+n]),i?"":s+"color: initial ; font-weight: initial")}},randomFloat(){return(window.crypto||window.msCrypto)?.getRandomValues(new Uint32Array(1))[0]/4294967295||Math.random()},refactor(){chatgpt.code.refactor()},regenerate(){chatgpt.response.regenerate()},renderHTML(s){var i,e=/<([a-z\d]+)\b([^>]*)>([\s\S]*?)<\/\1>/g,c=/(\S+)=['"]?((?:.(?!['"]?\s+\S+=|[>']))+.)['"]?/g,t=s.childNodes;chatgpt.renderHTML.preWrapSet||(s.style.whiteSpace="pre-wrap",chatgpt.renderHTML.preWrapSet=!0,setTimeout(()=>{chatgpt.renderHTML.preWrapSet=!1},100));for(i of t)if(i.nodeType==Node.TEXT_NODE){var l=i.nodeValue,d=Array.from(l.matchAll(e));if(0<d.length){let e=d[0],[t,r,o,a]=e.slice(0,4),n=document.createElement(r);n.textContent=a;Array.from(o.matchAll(c)).forEach(e=>{var t=e[1],e=e[2].replace(/['"]/g,"");n.setAttribute(t,e)});var d=chatgpt.renderHTML(n),g=document.createTextNode(l.substring(0,e.index)),l=document.createTextNode(l.substring(e.index+t.length));s.replaceChild(g,i),s.insertBefore(d,g.nextSibling),s.insertBefore(l,d.nextSibling)}}else i.nodeType==Node.ELEMENT_NODE&&chatgpt.renderHTML(i);return s},async resend(){chatgpt.send(await chatgpt.getChatData("latest","msg","user","latest"))},response:{continue(){try{chatgpt.getContinueBtn().click()}catch(e){console.error(e.message)}},get(){return(window.location.href.startsWith("https://chatgpt.com/c/")?this.getFromDOM:this.getFromAPI).apply(null,arguments)},getFromAPI(e,t){return e=e||"latest",t=t||"latest",chatgpt.getChatData(e,"msg","chatgpt",t)},getFromDOM(e){var t=document.querySelectorAll('div[data-testid*="conversation-turn"]:nth-child(odd)'),r=e.toString().toLowerCase();let o="";return t.length?o=(o=(/last|final/.test(r)?t[t.length-1]:t[(Number.isInteger(e)?e:/^\d+/.test(r)?/^\d+/.exec(r)[0]:(/^(?:1|one|fir)(?:st)?$/.test(r)?1:/^(?:2|tw(?:o|en|el(?:ve|f))|seco)(?:nd|t[yi])?(?:e?th)?$/.test(r)?2:/^(?:3|th(?:ree|ir?))(?:rd|teen|t[yi])?(?:e?th)?$/.test(r)?3:/^(?:4|fou?r)(?:teen|t[yi])?(?:e?th)?$/.test(r)?4:/^(?:5|fi(?:ve|f))(?:teen|t[yi])?(?:e?th)?$/.test(r)?5:/^(?:6|six)(?:teen|t[yi])?(?:e?th)?$/.test(r)?6:/^(?:7|seven)(?:teen|t[yi])?(?:e?th)?$/.test(r)?7:/^(?:8|eight?)(?:teen|t[yi])?(?:e?th)?$/.test(r)?8:/^(?:9|nine?)(?:teen|t[yi])?(?:e?th)?$/.test(r)?9:/^(?:10|ten)(?:th)?$/.test(r)?10:1)*(/(ty|ieth)$/.test(r)?10:1)+(/teen(th)?$/.test(r)?10:0))-1]).textContent).replace(/^ChatGPT(?:ChatGPT)?/,""):console.error("No conversation found!")},getLast(){return chatgpt.getChatData("active","msg","chatgpt","latest")},regenerate(){try{chatgpt.getRegenerateBtn().click()}catch(e){console.error(e.message)}},stopGenerating(){try{chatgpt.getStopBtn().click()}catch(e){console.error(e.message)}}},reviewCode(){chatgpt.code.review()},scrollToBottom(){try{chatgpt.getScrollBtn().click()}catch(e){console.error(e.message)}},send(e,r=""){for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string!`);let o=chatgpt.getChatBox();if(!o)return console.error("Chatbar element not found!");o.value=e,o.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(function e(){var t=chatgpt.getSendButton();t?.hasAttribute("disabled")?setTimeout(e,222):"click"==r.toLowerCase()||chatgpt.browser.isMobile()?t.click():o.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",bubbles:!0}))},222)},sendInNewChat(e){if("string"!=typeof e)return console.error("Message must be a string!");for(var t of document.querySelectorAll("nav a"))if(/(new|clear) chat/i.test(t.text)){t.click();break}setTimeout(()=>{chatgpt.send(e)},500)},settings:{scheme:{isDark(){return document.documentElement.classList.contains("dark")},isLight(){return document.documentElement.classList.contains("light")},set(e){var t=["dark","light","system"];if(!e)return console.error("Please specify a scheme value!");if(!t.includes(e))return console.error(`Invalid scheme value. Valid values are [${t}]`);let r=e;"system"==e&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),localStorage.setItem("theme",e),console.info(`Scheme set to ${e.toUpperCase()}.`),document.documentElement.classList.contains(r)||this.toggle()},toggle(){var[e,t]=this.isDark()?["dark","light"]:["light","dark"];document.documentElement.classList.replace(e,t),document.documentElement.style.colorScheme=t,localStorage.setItem("theme",t)}}},async sentiment(e,t){for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return chatgpt.send("What is the sentiment of the following text"+(t?` towards the entity ${t},`:"")+" from strongly negative to strongly positive?\n\n"+e),console.info("Analyzing sentiment..."),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")},setScheme(e){chatgpt.settings.scheme.set(e)},shareChat(s,i="clipboard"){var e=["alert","notify","notification","clipboard","copy"];if(!e.includes(i))return console.error("Invalid method '"+i+"' passed. Valid methods are ["+e+"].");return new Promise(r=>{chatgpt.getAccessToken().then(t=>{var a;a=t,new Promise((t,r)=>{let o=new XMLHttpRequest;chatgpt.getChatData(s).then(e=>{o.open("GET",chatgpt.endpoints.openAI.chat+"/"+e.id,!0),o.setRequestHeader("Content-Type","application/json"),o.setRequestHeader("Authorization","Bearer "+a),o.onload=()=>200!==o.status?r("🤖 chatgpt.js >> Request failed. Cannot retrieve chat node."):t(JSON.parse(o.responseText).current_node),o.send()})}).then(e=>{var a,n;a=t,n=e,new Promise((t,r)=>{let o=new XMLHttpRequest;chatgpt.getChatData(s).then(e=>{o.open("POST",chatgpt.endpoints.openAI.share_create,!0),o.setRequestHeader("Content-Type","application/json"),o.setRequestHeader("Authorization","Bearer "+a),o.onload=()=>200!==o.status?r("🤖 chatgpt.js >> Request failed. Cannot initialize share chat."):t(JSON.parse(o.responseText)),o.send(JSON.stringify({current_node_id:n,conversation_id:e.id,is_anonymous:!0}))})}).then(e=>{var o,a;o=t,a=e,new Promise((e,t)=>{let r=new XMLHttpRequest;r.open("PATCH",chatgpt.endpoints.openAI.share+"/"+a.share_id,!0),r.setRequestHeader("Content-Type","application/json"),r.setRequestHeader("Authorization","Bearer "+o),r.onload=()=>200!==r.status?t("🤖 chatgpt.js >> Request failed. Cannot share chat."):(console.info(`Chat shared at '${a.share_url}'`),e()),r.send(JSON.stringify({share_id:a.share_id,highlighted_message_id:a.highlighted_message_id,title:a.title,is_public:!0,is_visible:a.is_visible,is_anonymous:a.is_anonymous}))}).then(()=>{["copy","clipboard"].includes(i)?navigator.clipboard.writeText(e.share_url):chatgpt.alert("🚀 Share link created!",'"'+e.title+'" is available at: <a target="blank" rel="noopener" href="'+e.share_url+'" >'+e.share_url+"</a>",[function(){window.open(e.share_url,"_blank","noopener")},function(){navigator.clipboard.writeText(e.share_url)}]),r(e.share_url)})})})})})},showFooter(){chatgpt.getFooterDiv().style.display="revert"},showHeader(){chatgpt.getHeaderDiv().style.display="flex"},sidebar:{elements:[],observer:{},activateObserver(){if(this.observer instanceof MutationObserver)try{this.observer.disconnect()}catch(e){}if(!this.elements.length)return console.error("🤖 chatgpt.js >> No elements to append!");let t;for(var e of document.querySelectorAll("nav a"))if(/.*chat/.exec(e.text)[0]){t=e.classList,e.parentNode.style.margin="2px 0";break}this.elements.forEach(e=>{e.setAttribute("class",t),e.style.maxHeight=e.style.minHeight="44px",e.style.margin="2px 0"});let r=document.querySelector("nav");if(!r)return console.error("Sidebar element not found!");this.observer=new MutationObserver(e=>{e.forEach(e=>{("childList"==e.type&&e.addedNodes.length||"attributes"==e.type&&"data-chatgptjs"==e.attributeName)&&this.elements.forEach(e=>{if(!r.contains(e))try{r.insertBefore(e,r.querySelector("a").parentNode)}catch(e){console.error(e)}})})}),this.observer.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0})},append(e,t={}){var r=["button","dropdown"];if(!e||"string"!=typeof e)return console.error("🤖 chatgpt.js >> Please supply a valid string element name!");if(e=e.toLowerCase(),!r.includes(e))return console.error(`🤖 chatgpt.js >> Invalid element! Valid elements are [${r}]`);let o=document.createElement("dropdown"==e?"select":e);if(o.id=Math.floor(1e6*chatgpt.randomFloat())+Date.now(),"button"==e){o.textContent=t?.label&&"string"==typeof t.label?t.label:"chatgpt.js button";r=document.createElement("img");r.src=t?.icon&&"string"==typeof t.icon?t.icon:chatgpt.endpoints.assets+"/starters/chrome/extension/icons/icon128.png",r.width=18,o.insertBefore(r,o.firstChild),o.onclick=t?.onclick&&"function"==typeof t.onclick?t.onclick:function(){}}else if("dropdown"==e){if(t?.items&&Array.isArray(t.items)&&t.items.length||(t.items=[{text:"🤖 chatgpt.js option",value:"chatgpt.js option value"}]),!t.items.every(e=>"object"==typeof e))return console.error("'items' must be an array of objects!");t.items.forEach(e=>{var t=document.createElement("option");t.textContent=e?.text,t.value=e?.value,o.add(t)})}return"dropdown"==e&&(o.style.backgroundColor="var(--gray-900, rgb(32, 33, 35))"),this.elements.push(o),this.activateObserver(),document.body.setAttribute("data-chatgptjs","observer-trigger"),o.id},hide(){this.isOn()?this.toggle():console.info("Sidebar already hidden!")},show(){this.isOff()?this.toggle():console.info("Sidebar already shown!")},isOff(){return!this.isOn()},isOn(){var e=document.querySelector("body script + div > div");return e?chatgpt.browser.isMobile()?"hidden"==document.documentElement.style.overflow:"hidden"!=e.style.visibility&&"0px"!=e.style.width:console.error("Sidebar element not found!")},toggle(){var e,t=chatgpt.browser.isMobile(),r=t?()=>!0:e=>e.querySelector('svg path[d^="M8.857"]');for(e of document.querySelectorAll(t?"button":"nav button"))if(r(e))return void e.click()},async isLoaded(){return await chatgpt.isLoaded(),Promise.race([new Promise(t=>{!function e(){chatgpt.getNewChatLink()?t(!0):setTimeout(e,200)}()}),new Promise(e=>setTimeout(e,5e3))])}},startNewChat(){try{chatgpt.getNewChatBtn().click()}catch(e){console.error(e.message)}},stop(){chatgpt.response.stopGenerating()},async suggest(e,t){if(!e)return console.error("ideaType (1st argument) not supplied(e.g. 'gifts', 'names', 'recipes', etc.)");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string.`);return chatgpt.send("Suggest some names. "+(t||"")),console.info(`Creating ${e}...`),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")},speak(e,t={}){var r,{voice:o=2,pitch:a=2,speed:n=1.1}=t;if("string"!=typeof e)return console.error("Message must be a string!");for(r in t){var s=t[r];if("number"!=typeof s&&!/^\d+$/.test(s))return console.error(`Invalid ${r} index '${s}'. Must be a number!`)}try{var i=speechSynthesis.getVoices(),c=new SpeechSynthesisUtterance;c.text=e,c.voice=i[o],c.pitch=a,c.rate=n,speechSynthesis.speak(c)}catch(e){console.error(e)}},async summarize(e){return e?"string"!=typeof e?console.error("Text argument must be a string!"):(chatgpt.send("Summarize the following text:\n\n"+e),console.info("Summarizing text..."),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")):console.error("Text (1st) argument not supplied. Pass some text!")},toggleScheme(){chatgpt.settings.scheme.toggle()},async translate(e,t){if(!e)return console.error("Text (1st) argument not supplied. Pass some text!");if(!t)return console.error("outputLang (2nd) argument not supplied. Pass a language!");for(let e=0;e<arguments.length;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string!`);return chatgpt.send("Translate the following text to "+t+". Only reply with the translation.\n\n"+e),console.info("Translating text..."),await chatgpt.isIdle(),chatgpt.getChatData("active","msg","chatgpt","latest")},unminify(){chatgpt.code.unminify()},uuidv4(){let r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{var t=(r+window.crypto.getRandomValues(new Uint32Array(1))[0]/(Math.pow(2,32)-1)*16)%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})},writeCode(){chatgpt.code.write()}},cjsBtnActions=(chatgpt.scheme={...chatgpt.settings.scheme},["click","get"]),cjsTargetTypes=["button","link","div","response"];for(let t of cjsBtnActions)chatgpt[t+"Button"]=function(r){var e=/^[.#]/.test(r)?document.querySelector(r):/send/i.test(r)?document.querySelector('form button[class*="bottom"]'):/scroll/i.test(r)?document.querySelector('button[class*="cursor"]'):(()=>{for(var e of document.querySelectorAll("button"))if(e.textContent.toLowerCase().includes(r.toLowerCase()))return e;for(var t of document.querySelectorAll("nav a"))if(t.textContent.toLowerCase().includes(r.toLowerCase()))return t})();if("click"!=t)return e;e.click()};let cjsFuncAliases=[["actAs","actas","act","become","persona","premadePrompt","preMadePrompt","prePrompt","preprompt","roleplay","rolePlay","rp"],["activateAutoRefresh","activateAutoRefresher","activateRefresher","activateSessionRefresher","autoRefresh","autoRefresher","autoRefreshSession","refresher","sessionRefresher"],["continue","continueChat","continueGenerating","continueResponse"],["deactivateAutoRefresh","deactivateAutoRefresher","deactivateRefresher","deactivateSessionRefresher"],["detectLanguage","getLanguage"],["executeCode","codeExecute"],["exportChat","chatExport","export"],["getFooterDiv","getFooter"],["getHeaderDiv","getHeader"],["getLastPrompt","getLastQuery","getMyLastMsg","getMyLastQuery"],["getContinueGeneratingButton","getContinueButton"],["getScrollToBottomButton","getScrollButton"],["getStopGeneratingButton","getStopButton"],["getTextarea","getTextArea","getChatbox","getChatBox"],["isFullScreen","isFullscreen","isfullscreen"],["isLoaded","isloaded"],["logOut","logout","logOff","logoff","signOut","signout","signOff","signoff"],["minify","codeMinify","minifyCode"],["new","newChat","startNewChat"],["obfuscate","codeObfuscate","obfuscateCode"],["printAllFunctions","showAllFunctions"],["refactor","codeRefactor","refactorCode"],["refreshReply","regenerate","regenerateReply"],["refreshSession","sessionRefresh"],["renderHTML","renderHtml","renderLinks","renderTags"],["reviewCode","codeReview"],["send","sendChat","sendMsg"],["sendInNewChat","sendNewChat"],["sentiment","analyzeSentiment","sentimentAnalysis"],["startNewChat","new","newChat"],["stop","stopChat","stopGenerating","stopResponse"],["suggest","suggestion","recommend"],["toggleAutoRefresh","toggleAutoRefresher","toggleRefresher","toggleSessionRefresher"],["toggleScheme","toggleMode"],["translate","translation","translator"],["unminify","unminifyCode","codeUnminify"],["writeCode","codeWrite"]],cjsFuncSynonyms=[["account","acct"],["activate","turnOn"],["analyze","check","evaluate","review"],["ask","send","submit"],["button","btn"],["continue","resume"],["chats","history"],["chat","conversation","convo"],["clear","delete","remove"],["data","details"],["deactivate","deActivate","turnOff"],["execute","interpret","interpreter","run"],["firefox","ff"],["generating","generation"],["minify","uglify"],["refactor","rewrite"],["regenerate","regen"],["render","parse"],["reply","response"],["sentiment","attitude","emotion","feeling","opinion","perception"],["speak","say","speech","talk","tts"],["summarize","tldr"],["unminify","beautify","prettify","prettyPrint"]],camelCaser=e=>e.map((e,t)=>0===t||"s"==e?e:e.charAt(0).toUpperCase()+e.slice(1)).join("");for(let o in chatgpt){for(let r of cjsFuncAliases)if(r.includes(o))if(r.some(e=>e.includes("."))){let t=r.find(e=>e.includes(".")).split(".")[1];for(let e of r)/^(\w+)/.exec(e)[1]!==o&&(chatgpt[e]=chatgpt[o][t])}else for(let e of r)e!==o&&(chatgpt[e]=chatgpt[o]);do{var newFunctionsCreated=!1;for(let a in chatgpt)if("function"==typeof chatgpt[a]){let o=a.split(/(?=[A-Zs])/);for(let r of o){let e=[].concat(...cjsFuncSynonyms.filter(e=>e.includes(r.toLowerCase())).map(e=>e.filter(e=>e!==r.toLowerCase())));for(let t of e){let e=camelCaser(o.map(e=>e==r?t:e));chatgpt[e]||(chatgpt[e]=chatgpt[a],newFunctionsCreated=!0)}}}}while(newFunctionsCreated)}let consolePrefix="🤖 chatgpt.js >> ",ogError=console.error,ogInfo=console.info;console.error=(...e)=>{e[0].startsWith(consolePrefix)?ogError(...e):ogError(consolePrefix+e[0],...e.slice(1))},console.info=e=>{e.startsWith(consolePrefix)?ogInfo(e):ogInfo(consolePrefix+e)};try{window.chatgpt=chatgpt}catch(e){}try{module.exports=chatgpt}catch(e){}
package/docs/README.md CHANGED
@@ -45,8 +45,8 @@
45
45
  [![](https://img.shields.io/github/stars/KudoAI/chatgpt.js?label=Stars&color=af68ff&logo=github&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/stargazers)
46
46
  [![](https://img.shields.io/badge/License-MIT-green.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/blob/main/LICENSE.md)
47
47
  [![](https://img.shields.io/github/commit-activity/m/KudoAI/chatgpt.js?label=Commits&logo=github&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/commits/main)
48
- ![](https://img.shields.io/badge/Clones-326/month-869da0?logo=github&logoColor=white&labelColor=464646&style=for-the-badge)
49
- [![](https://img.shields.io/github/size/KudoAI/chatgpt.js/dist/chatgpt.min.js?branch=v3.0.3&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/tree/v3.0.3/dist/chatgpt.min.js)
48
+ ![](https://img.shields.io/badge/Clones-390/month-869da0?logo=github&logoColor=white&labelColor=464646&style=for-the-badge)
49
+ [![](https://img.shields.io/github/size/KudoAI/chatgpt.js/dist/chatgpt.min.js?branch=v3.1.0&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge)](https://github.com/KudoAI/chatgpt.js/tree/v3.1.0/dist/chatgpt.min.js)
50
50
  [![](https://img.shields.io/codefactor/grade/github/kudoai/chatgpt.js?label=Code+Quality&logo=codefactor&logoColor=white&labelColor=464646&color=1acc6c&style=for-the-badge)](https://www.codefactor.io/repository/github/kudoai/chatgpt.js)
51
51
  [![](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dkudoai_chatgpt.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold)](https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=kudoai_chatgpt.js)
52
52
  [![](https://img.shields.io/badge/Mentioned_in-Awesome-cca8c4?logo=awesomelists&logoColor=white&labelColor=464646&style=for-the-badge)](https://github.com/sindresorhus/awesome-chatgpt#javascript)
@@ -84,7 +84,7 @@
84
84
 
85
85
  ```js
86
86
  (async () => {
87
- await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js');
87
+ await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js');
88
88
  // Your code here...
89
89
  })();
90
90
  ```
@@ -93,7 +93,7 @@
93
93
 
94
94
  ```js
95
95
  var xhr = new XMLHttpRequest();
96
- xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js');
96
+ xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js');
97
97
  xhr.onload = function () {
98
98
  if (xhr.status === 200) {
99
99
  var chatgptJS = document.createElement('script');
@@ -115,7 +115,7 @@ function yourCode() {
115
115
 
116
116
  ```js
117
117
  ...
118
- // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js
118
+ // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js
119
119
  // ==/UserScript==
120
120
 
121
121
  // Your code here...
@@ -190,7 +190,7 @@ chatgpt.get('reply', 'last');
190
190
 
191
191
  Each call equally fetches the last response. If you think it works, it probably will... so just type it!
192
192
 
193
- If it didn't, check out the extended [userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.0.3/docs/USERGUIDE.md), or simply submit an [issue](https://github.com/KudoAI/chatgpt.js/issues) or [PR](https://github.com/KudoAI/chatgpt.js/pulls) and it will be integrated, ezpz!
193
+ If it didn't, check out the extended [userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.1.0/docs/USERGUIDE.md), or simply submit an [issue](https://github.com/KudoAI/chatgpt.js/issues) or [PR](https://github.com/KudoAI/chatgpt.js/pulls) and it will be integrated, ezpz!
194
194
 
195
195
  <img height=8px width="100%" src="https://media.chatgptjs.org/images/separators/gradient-aqua.png?78210a7">
196
196
 
@@ -360,7 +360,7 @@ This library exists thanks to code, translations, issues & ideas from the follow
360
360
  <div align="center">
361
361
 
362
362
  **[Releases](https://github.com/KudoAI/chatgpt.js/releases)** /
363
- [Userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.0.3/docs/USERGUIDE.md) /
363
+ [Userguide](https://github.com/KudoAI/chatgpt.js/blob/v3.1.0/docs/USERGUIDE.md) /
364
364
  [Discuss](https://github.com/KudoAI/chatgpt.js/discussions) /
365
365
  <a href="#--------------------------------------------------------------------------------english---------简体中文---------繁體中文---------日本---------한국인---------हिंदी---------नेपाली---------deutsch---------español---------français---------italiano---------nederlands---------português---------việt----">Back to top ↑</a>
366
366
 
package/docs/USERGUIDE.md CHANGED
@@ -150,7 +150,7 @@
150
150
 
151
151
  ```js
152
152
  (async () => {
153
- await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js');
153
+ await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js');
154
154
  // Your code here...
155
155
  })();
156
156
  ```
@@ -159,7 +159,7 @@
159
159
 
160
160
  ```js
161
161
  var xhr = new XMLHttpRequest();
162
- xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js');
162
+ xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js');
163
163
  xhr.onload = function () {
164
164
  if (xhr.status === 200) {
165
165
  var chatgptJS = document.createElement('script');
@@ -181,7 +181,7 @@ function yourCode() {
181
181
 
182
182
  ```js
183
183
  ...
184
- // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js
184
+ // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js
185
185
  // ==/UserScript==
186
186
 
187
187
  // Your code here...
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kudoai/chatgpt.js",
3
- "version": "3.0.3",
3
+ "version": "3.1.0",
4
4
  "description": "Client-side JavaScript library for ChatGPT",
5
5
  "author": {
6
6
  "name": "KudoAI & contributors",
@@ -64,7 +64,7 @@
64
64
  "url": "https://github.com/sponsors/KudoAI"
65
65
  },
66
66
  "devDependencies": {
67
- "@adamlui/minify.js": "^1.8.3",
67
+ "@adamlui/minify.js": "^1.8.4",
68
68
  "@adamlui/scss-to-css": "^1.10.3",
69
69
  "docsify-cli": "^4.4.4",
70
70
  "eslint": "^9.9.1",
@@ -85,9 +85,10 @@ const chatgpt = { // eslint-disable-line no-redeclare
85
85
  document.head.append(modalStyle);
86
86
  }
87
87
  modalStyle.innerText = ( // update prev/new style contents
88
+ '.no-mobile-tap-outline { outline: none ; -webkit-tap-highlight-color: transparent }'
88
89
 
89
90
  // Background styles
90
- '.chatgpt-modal {'
91
+ + '.chatgpt-modal {'
91
92
  + 'position: fixed ; top: 0 ; left: 0 ; width: 100% ; height: 100% ;' // expand to full view-port
92
93
  + 'background-color: rgba(67, 70, 72, 0) ;' // init dim bg but no opacity
93
94
  + 'transition: background-color 0.05s ease ;' // speed to transition in show alert routine
@@ -148,7 +149,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
148
149
 
149
150
  // Create/append buttons (if provided) to buttons div
150
151
  const modalButtons = document.createElement('div');
151
- modalButtons.classList.add('modal-buttons');
152
+ modalButtons.classList.add('modal-buttons', 'no-mobile-tap-outline');
152
153
  if (btns) { // are supplied
153
154
  if (!Array.isArray(btns)) btns = [btns]; // convert single button to array if necessary
154
155
  btns.forEach((buttonFn) => { // create title-cased labels + attach listeners
@@ -157,7 +158,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
157
158
  .replace(/[_-]\w/g, match => match.slice(1).toUpperCase()) // convert snake/kebab to camel case
158
159
  .replace(/([A-Z])/g, ' $1') // insert spaces
159
160
  .replace(/^\w/, firstChar => firstChar.toUpperCase()); // capitalize first letter
160
- button.addEventListener('click', () => { dismissAlert(); buttonFn(); });
161
+ button.onclick = () => { dismissAlert(); buttonFn(); };
161
162
  modalButtons.insertBefore(button, modalButtons.firstChild); // insert button to left
162
163
  });
163
164
  }
@@ -177,12 +178,11 @@ const chatgpt = { // eslint-disable-line no-redeclare
177
178
  const checkboxFn = checkbox, // assign the named function to checkboxFn
178
179
  checkboxInput = document.createElement('input');
179
180
  checkboxInput.type = 'checkbox';
180
- checkboxInput.addEventListener('change', checkboxFn);
181
+ checkboxInput.onchange = checkboxFn;
181
182
 
182
183
  // Create/show label
183
184
  const checkboxLabel = document.createElement('label');
184
- checkboxLabel.addEventListener('click', () => {
185
- checkboxInput.checked = !checkboxInput.checked; checkboxFn(); });
185
+ checkboxLabel.onclick = () => { checkboxInput.checked = !checkboxInput.checked; checkboxFn(); };
186
186
  checkboxLabel.textContent = checkboxFn.name.charAt(0).toUpperCase() // capitalize first char
187
187
  + checkboxFn.name.slice(1) // format remaining chars
188
188
  .replace(/([A-Z])/g, (match, letter) => ' ' + letter.toLowerCase()) // insert spaces, convert to lowercase
@@ -194,7 +194,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
194
194
 
195
195
  // Create close button
196
196
  const closeBtn = document.createElement('div');
197
- closeBtn.title = 'Close'; closeBtn.classList.add('modal-close-btn');
197
+ closeBtn.title = 'Close'; closeBtn.classList.add('modal-close-btn', 'no-mobile-tap-outline');
198
198
  const closeSVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
199
199
  closeSVG.setAttribute('height', '10px');
200
200
  closeSVG.setAttribute('viewBox', '0 0 14 14');
@@ -247,8 +247,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
247
247
 
248
248
  // Add listeners to dismiss alert
249
249
  const dismissElems = [modalContainer, closeBtn, closeSVG, dismissBtn];
250
- dismissElems.forEach(elem => {
251
- elem.addEventListener('click', clickHandler); });
250
+ dismissElems.forEach(elem => elem.onclick = clickHandler);
252
251
  document.addEventListener('keydown', keyHandler);
253
252
 
254
253
  // Define alert dismisser
@@ -262,10 +261,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
262
261
  alertQueue = JSON.parse(localStorage.alertQueue);
263
262
  alertQueue.shift(); // + memory
264
263
  localStorage.alertQueue = JSON.stringify(alertQueue); // + storage
265
-
266
- // Remove all listeners to prevent memory leaks
267
- dismissElems.forEach(elem => { elem.removeEventListener('click', clickHandler); });
268
- document.removeEventListener('keydown', keyHandler);
264
+ document.removeEventListener('keydown', keyHandler); // prevent memory leaks
269
265
 
270
266
  // Check for pending alerts in queue
271
267
  if (alertQueue.length > 0) {
@@ -300,8 +296,10 @@ const chatgpt = { // eslint-disable-line no-redeclare
300
296
  const randomDelay = Math.max(2, Math.floor(chatgpt.randomFloat() * 21 - 10)); // set random delay up to ±10 secs
301
297
  autoRefresh.isActive = setTimeout(() => {
302
298
  const manifestScript = document.querySelector('script[src*="_ssgManifest.js"]');
303
- document.querySelector('#refresh-frame').src = manifestScript.src + '?' + Date.now();
304
- console.log('↻ ChatGPT >> [' + autoRefresh.nowTimeStamp() + '] ChatGPT session refreshed');
299
+ if (manifestScript) {
300
+ document.querySelector('#refresh-frame').src = manifestScript.src + '?' + Date.now();
301
+ console.log('↻ ChatGPT >> [' + autoRefresh.nowTimeStamp() + '] ChatGPT session refreshed');
302
+ }
305
303
  scheduleRefreshes(interval);
306
304
  }, (interval + randomDelay) * 1000);
307
305
  };
@@ -309,8 +307,8 @@ const chatgpt = { // eslint-disable-line no-redeclare
309
307
  console.log('↻ ChatGPT >> [' + chatgpt.autoRefresh.nowTimeStamp() + '] Auto refresh activated');
310
308
 
311
309
  // Add listener to send beacons in Chromium to thwart auto-discards if Page Visibility API supported
312
- if (navigator.userAgent.includes('Chrome') && typeof document.hidden !== 'undefined') {
313
- document.addEventListener('visibilitychange', this.toggle.beacons); }
310
+ if (navigator.userAgent.includes('Chrome') && typeof document.hidden !== 'undefined')
311
+ document.addEventListener('visibilitychange', this.toggle.beacons);
314
312
  },
315
313
 
316
314
  deactivate() {
@@ -421,20 +419,20 @@ const chatgpt = { // eslint-disable-line no-redeclare
421
419
  await new Promise(resolve => { // when reply starts generating
422
420
  (function checkReplyExists() {
423
421
  const msgDivs = document.querySelectorAll('div[data-message-author-role]');
424
- msgDivs[msgDivs.length - 1].dataset.messageAuthorRole == 'assistant' ? resolve(true)
422
+ msgDivs[msgDivs.length - 1]?.dataset.messageAuthorRole == 'assistant' ? resolve(true)
425
423
  : setTimeout(checkReplyExists, 200); })();
426
424
  });
427
425
  const lastReplyDiv = await new Promise(resolve => { // when code starts generating
428
426
  (function checkPreExists() {
429
427
  const replyDivs = document.querySelectorAll('div[data-message-author-role="assistant"]'),
430
428
  lastReplyDiv = replyDivs[replyDivs.length - 1];
431
- lastReplyDiv.querySelector('pre') ? resolve(lastReplyDiv)
429
+ lastReplyDiv?.querySelector('pre') ? resolve(lastReplyDiv)
432
430
  : setTimeout(checkPreExists, 200); })();
433
431
  });
434
432
  return Promise.race([
435
433
  new Promise(resolve => { // when code block not last child of reply div
436
434
  (function checkPreNotLast() {
437
- lastReplyDiv.querySelector('pre').nextElementSibling ? resolve(true)
435
+ lastReplyDiv?.querySelector('pre').nextElementSibling ? resolve(true)
438
436
  : setTimeout(checkPreNotLast, 200); })();
439
437
  }), chatgpt.isIdle() // ...or reply stopped generating
440
438
  ]);
@@ -544,9 +542,9 @@ const chatgpt = { // eslint-disable-line no-redeclare
544
542
  const msgs = []; let isUserMsg = true;
545
543
  chatDivs.forEach((div) => {
546
544
  const sender = isUserMsg ? 'USER' : 'CHATGPT'; isUserMsg = !isUserMsg;
547
- let msg = Array.from(div.childNodes).map(node => node.innerText)
548
- .join('\n\n') // insert double line breaks between paragraphs
549
- .replace('Copy code', '');
545
+ const msg = Array.from(div.childNodes).map(node => node.innerText)
546
+ .join('\n\n') // insert double line breaks between paragraphs
547
+ .replace('Copy code', '');
550
548
  msgs.push(sender + ': ' + msg);
551
549
  });
552
550
  transcript = msgs.join('\n\n');
@@ -567,7 +565,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
567
565
  // Format filename after <title>
568
566
  const parser = new DOMParser(),
569
567
  parsedHtml = parser.parseFromString(htmlContent, 'text/html');
570
- filename = parsedHtml.querySelector('title').textContent + '.html';
568
+ filename = `${ parsedHtml.querySelector('title').textContent || 'ChatGPT conversation' }.html`;
571
569
 
572
570
  // Convert relative CSS paths to absolute ones
573
571
  const cssLinks = parsedHtml.querySelectorAll('link[rel="stylesheet"]');
@@ -864,15 +862,15 @@ const chatgpt = { // eslint-disable-line no-redeclare
864
862
  return formBtnSVG.parentNode.parentNode;
865
863
  }},
866
864
 
867
- getFooterDiv() { return document.querySelector('main form').parentNode.parentNode.nextElementSibling; },
865
+ getFooterDiv() { return document.querySelector('main form')?.parentNode.parentNode.nextElementSibling; },
868
866
  getHeaderDiv() { return document.querySelector('main .sticky'); },
869
867
  getLastPrompt() { return chatgpt.getChatData('active', 'msg', 'user', 'latest'); },
870
868
  getLastResponse() { return chatgpt.getChatData('active', 'msg', 'chatgpt', 'latest'); },
871
869
 
872
870
  getNewChatButton() {
873
871
  for (const navBtnSVG of document.querySelectorAll('nav button svg'))
874
- if (navBtnSVG.querySelector('path[d*="M15.673 3.913a3.121"], ' // pencil-on-pad icon
875
- + 'path[d*="M3.07 10.876C3.623"]')) // refresh icon if temp chat
872
+ if (navBtnSVG.querySelector('path[d^="M15.6729"], ' // pencil-on-pad icon
873
+ + 'path[d^="M3.06957"]')) // refresh icon if temp chat
876
874
  return navBtnSVG.parentNode;
877
875
  },
878
876
 
@@ -1134,7 +1132,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1134
1132
  const optionButtons = document.querySelectorAll('a[role="menuitem"]');
1135
1133
  let cssClasses;
1136
1134
 
1137
- for (let navLink of optionButtons)
1135
+ for (const navLink of optionButtons)
1138
1136
  if (navLink.textContent == 'Settings') {
1139
1137
  cssClasses = navLink.classList;
1140
1138
  break; }
@@ -1152,7 +1150,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1152
1150
  this.elements.push(newElement);
1153
1151
  const menuBtn = document.querySelector('nav button[id*="headless"]');
1154
1152
  if (!this.addedEvent) { // to prevent adding more than one event
1155
- menuBtn.addEventListener('click', () => { setTimeout(addElementsToMenu, 25); });
1153
+ menuBtn?.addEventListener('click', () => { setTimeout(addElementsToMenu, 25); });
1156
1154
  this.addedEvent = true; }
1157
1155
 
1158
1156
  return newElement.id; // Return the element id
@@ -1171,7 +1169,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1171
1169
 
1172
1170
  minify() { chatgpt.code.minify(); },
1173
1171
 
1174
- async notify(msg, position, notifDuration, shadow) {
1172
+ notify(msg, position, notifDuration, shadow) {
1175
1173
  notifDuration = notifDuration ? +notifDuration : 1.75; // sec duration to maintain notification visibility
1176
1174
  const fadeDuration = 0.35, // sec duration of fade-out
1177
1175
  vpYoffset = 23, vpXoffset = 27; // px offset from viewport border
@@ -1185,7 +1183,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1185
1183
 
1186
1184
  // Create/append close button
1187
1185
  const closeBtn = document.createElement('div');
1188
- closeBtn.title = 'Dismiss'; closeBtn.classList.add('notif-close-btn');
1186
+ closeBtn.title = 'Dismiss'; closeBtn.classList.add('notif-close-btn', 'no-mobile-tap-outline');
1189
1187
  const closeSVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
1190
1188
  closeSVG.setAttribute('height', '8px');
1191
1189
  closeSVG.setAttribute('viewBox', '0 0 14 14');
@@ -1215,6 +1213,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1215
1213
  }
1216
1214
  notifStyle.innerText = ( // update prev/new style contents
1217
1215
  '.chatgpt-notif {'
1216
+ + '.no-mobile-tap-outline { outline: none ; -webkit-tap-highlight-color: transparent }'
1218
1217
  + 'background-color: black ; padding: 10px 13px 10px 18px ; border-radius: 11px ; border: 1px solid #f5f5f7 ;' // bubble style
1219
1218
  + 'opacity: 0 ; position: fixed ; z-index: 9999 ; font-size: 1.8rem ; color: white ;' // visibility
1220
1219
  + '-webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ;'
@@ -1270,15 +1269,17 @@ const chatgpt = { // eslint-disable-line no-redeclare
1270
1269
  clearTimeout(dismissFuncTID);
1271
1270
  };
1272
1271
  const dismissFuncTID = setTimeout(dismissNotif, hideDelay * 1000); // maintain visibility for `hideDelay` secs, then dismiss
1273
- closeSVG.addEventListener('click', dismissNotif, { once: true }); // add to close button clicks
1272
+ closeSVG.onclick = dismissNotif; // add to close button clicks
1274
1273
 
1275
1274
  // Destroy notification
1276
- notificationDiv.addEventListener('animationend', () => {
1275
+ notificationDiv.onanimationend = () => {
1277
1276
  notificationDiv.remove(); // remove from DOM
1278
1277
  notifyProps = JSON.parse(localStorage.notifyProps);
1279
1278
  notifyProps.queue[notificationDiv.quadrant].shift(); // + memory
1280
1279
  localStorage.notifyProps = JSON.stringify(notifyProps); // + storage
1281
- }, { once: true });
1280
+ };
1281
+
1282
+ return notificationDiv;
1282
1283
  },
1283
1284
 
1284
1285
  obfuscate() { chatgpt.code.obfuscate(); },
@@ -1437,36 +1438,35 @@ const chatgpt = { // eslint-disable-line no-redeclare
1437
1438
  const responseDivs = document.querySelectorAll('div[data-testid*="conversation-turn"]:nth-child(odd)'),
1438
1439
  strPos = pos.toString().toLowerCase();
1439
1440
  let response = '';
1440
- if (responseDivs.length) {
1441
- if (/last|final/.test(strPos)) // get last response
1442
- response = responseDivs[responseDivs.length - 1].textContent;
1443
- else { // get nth response
1444
- const nthOfResponse = (
1445
-
1446
- // Calculate base number
1447
- Number.isInteger(pos) ? pos : // do nothing for integers
1448
- /^\d+/.test(strPos) ? /^\d+/.exec(strPos)[0] : // extract first digits for strings w/ them
1449
- ( // convert words to integers for digitless strings
1450
- /^(?:1|one|fir)(?:st)?$/.test(strPos) ? 1
1451
- : /^(?:2|tw(?:o|en|el(?:ve|f))|seco)(?:nd|t[yi])?(?:e?th)?$/.test(strPos) ? 2
1452
- : /^(?:3|th(?:ree|ir?))(?:rd|teen|t[yi])?(?:e?th)?$/.test(strPos) ? 3
1453
- : /^(?:4|fou?r)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 4
1454
- : /^(?:5|fi(?:ve|f))(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 5
1455
- : /^(?:6|six)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 6
1456
- : /^(?:7|seven)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 7
1457
- : /^(?:8|eight?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 8
1458
- : /^(?:9|nine?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 9
1459
- : /^(?:10|ten)(?:th)?$/.test(strPos) ? 10 : 1 )
1460
-
1461
- // Transform base number if suffixed
1462
- * ( /(ty|ieth)$/.test(strPos) ? 10 : 1 ) // x 10 if -ty/ieth
1463
- + ( /teen(th)?$/.test(strPos) ? 10 : 0 ) // + 10 if -teen/teenth
1464
-
1465
- );
1466
- response = responseDivs[nthOfResponse - 1].textContent;
1467
- }
1468
- response = response.replace(/^ChatGPT(?:ChatGPT)?/, ''); // strip sender name
1441
+ if (!responseDivs.length) return console.error('No conversation found!');
1442
+ if (/last|final/.test(strPos)) // get last response
1443
+ response = responseDivs[responseDivs.length - 1].textContent;
1444
+ else { // get nth response
1445
+ const nthOfResponse = (
1446
+
1447
+ // Calculate base number
1448
+ Number.isInteger(pos) ? pos : // do nothing for integers
1449
+ /^\d+/.test(strPos) ? /^\d+/.exec(strPos)[0] : // extract first digits for strings w/ them
1450
+ ( // convert words to integers for digitless strings
1451
+ /^(?:1|one|fir)(?:st)?$/.test(strPos) ? 1
1452
+ : /^(?:2|tw(?:o|en|el(?:ve|f))|seco)(?:nd|t[yi])?(?:e?th)?$/.test(strPos) ? 2
1453
+ : /^(?:3|th(?:ree|ir?))(?:rd|teen|t[yi])?(?:e?th)?$/.test(strPos) ? 3
1454
+ : /^(?:4|fou?r)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 4
1455
+ : /^(?:5|fi(?:ve|f))(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 5
1456
+ : /^(?:6|six)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 6
1457
+ : /^(?:7|seven)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 7
1458
+ : /^(?:8|eight?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 8
1459
+ : /^(?:9|nine?)(?:teen|t[yi])?(?:e?th)?$/.test(strPos) ? 9
1460
+ : /^(?:10|ten)(?:th)?$/.test(strPos) ? 10 : 1 )
1461
+
1462
+ // Transform base number if suffixed
1463
+ * ( /(ty|ieth)$/.test(strPos) ? 10 : 1 ) // x 10 if -ty/ieth
1464
+ + ( /teen(th)?$/.test(strPos) ? 10 : 0 ) // + 10 if -teen/teenth
1465
+
1466
+ );
1467
+ response = responseDivs[nthOfResponse - 1].textContent;
1469
1468
  }
1469
+ response = response.replace(/^ChatGPT(?:ChatGPT)?/, ''); // strip sender name
1470
1470
  return response;
1471
1471
  },
1472
1472
 
@@ -1481,7 +1481,8 @@ const chatgpt = { // eslint-disable-line no-redeclare
1481
1481
  send(msg, method='') {
1482
1482
  for (let i = 0; i < arguments.length; i++) if (typeof arguments[i] !== 'string')
1483
1483
  return console.error(`Argument ${ i + 1 } must be a string!`);
1484
- const textArea = document.querySelector('form textarea');
1484
+ const textArea = chatgpt.getChatBox();
1485
+ if (!textArea) return console.error('Chatbar element not found!');
1485
1486
  textArea.value = msg;
1486
1487
  textArea.dispatchEvent(new Event('input', { bubbles: true })); // enable send button
1487
1488
  setTimeout(function delaySend() {
@@ -1653,8 +1654,9 @@ const chatgpt = { // eslint-disable-line no-redeclare
1653
1654
  element.style.margin = '2px 0';
1654
1655
  });
1655
1656
 
1656
- const navBar = document.querySelector('nav');
1657
1657
  // Create MutationObserver instance
1658
+ const navBar = document.querySelector('nav');
1659
+ if (!navBar) return console.error('Sidebar element not found!');
1658
1660
  this.observer = new MutationObserver(mutations => {
1659
1661
  mutations.forEach(mutation => {
1660
1662
  if ((mutation.type == 'childList' && mutation.addedNodes.length) ||
@@ -1740,6 +1742,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1740
1742
  isOff() { return !this.isOn(); },
1741
1743
  isOn() {
1742
1744
  const sidebar = document.querySelector('body script + div > div');
1745
+ if (!sidebar) return console.error('Sidebar element not found!');
1743
1746
  return chatgpt.browser.isMobile() ?
1744
1747
  document.documentElement.style.overflow == 'hidden'
1745
1748
  : sidebar.style.visibility != 'hidden' && sidebar.style.width != '0px';
@@ -1749,7 +1752,7 @@ const chatgpt = { // eslint-disable-line no-redeclare
1749
1752
  const isMobileDevice = chatgpt.browser.isMobile(),
1750
1753
  navBtnSelector = isMobileDevice ? 'button' : 'nav button',
1751
1754
  isToggleBtn = isMobileDevice ? () => true // since 1st one is toggle
1752
- : btn => btn.querySelector('svg path[d*="M8.857 3h6.286c1.084"]');
1755
+ : btn => btn.querySelector('svg path[d^="M8.857"]');
1753
1756
  for (const btn of document.querySelectorAll(navBtnSelector))
1754
1757
  if (isToggleBtn(btn)) { btn.click(); return; }
1755
1758
  },
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "name": "ChatGPT Extension",
4
4
  "description": "A Chrome template to start using chatgpt.js like a boss!",
5
- "version": "2024.8.28",
5
+ "version": "2024.8.29",
6
6
  "author": "chatgpt.js",
7
7
  "icons": {
8
8
  "16": "icons/icon16.png",
@@ -3,13 +3,13 @@
3
3
  // @description A Greasemonkey template to start using chatgpt.js like a boss
4
4
  // @author chatgpt.js
5
5
  // @namespace https://chatgpt.js.org
6
- // @version 2024.8.28.1
6
+ // @version 2024.8.29
7
7
  // @license MIT
8
8
  // @match *://chatgpt.com/*
9
9
  // @match *://chat.openai.com/*
10
- // @icon https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@3.0.3/starters/greasemonkey/media/images/icons/robot/icon48.png
11
- // @icon64 https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@3.0.3/starters/greasemonkey/media/images/icons/robot/icon64.png
12
- // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.0.3/dist/chatgpt.min.js
10
+ // @icon https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@3.1.0/starters/greasemonkey/media/images/icons/robot/icon48.png
11
+ // @icon64 https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@3.1.0/starters/greasemonkey/media/images/icons/robot/icon64.png
12
+ // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.1.0/dist/chatgpt.min.js
13
13
  // @grant GM_getValue
14
14
  // @grant GM_setValue
15
15
  // @noframes