crdtuxp.js

  1. /**
  2. * Creative Developer Tools (CRDT) is a growing suite of tools aimed at script developers and plug-in<br>
  3. * developers for the Adobe Creative Cloud eco-system.<br>
  4. * <br>
  5. * There are two different versions of CRDT: one for UXP/UXPScript and another for ExtendScript.<br>
  6. * <br>
  7. * For downloading and installation info, visit<br>
  8. * <br>
  9. * https://CreativeDeveloperTools.com
  10. * <br>
  11. * <code>crdtuxp</code> contains a number of useful functions. Some of these functions are implemented in JavaScript<br>
  12. * in <code>crdtux.js</code> and are synchronous.<br>
  13. * <br>
  14. * Other functions are delegated to a daemon process, and are always asynchronous.<br>
  15. * <br>
  16. * The list of endpoints is further down<br>
  17. * <br>
  18. * <code>crdtuxp</code> steps out of the UXP security sandbox - which means that as a developer, you need to be<br>
  19. * judicious when using this.<br>
  20. * <br>
  21. * Every solution operates in a unique context. The UXP security measures are helpful in keeping things<br>
  22. * secure, but in many situations, they are a massive overkill.<br>
  23. * <br>
  24. * It should be up to the user/developer/IT department to decide how to handle security.<br>
  25. * <br>
  26. * Sometimes the whole workflow can live inside walled garden, on a disconnected network, without any<br>
  27. * contact with the outside world and not be allowed to run any unvetted software.<br>
  28. * <br>
  29. * Or sometimes the OS security is safe enough for the workflow at hand.<br>
  30. * <br>
  31. * In those cases, the UXP security measures are counter-productive: they represent unnessary hurdles to<br>
  32. * the software development, or make the user interace clunky and user-unfriendly.<br>
  33. * <br>
  34. * Using the UXP sandboxing should be a developer-selectable option, not an enforced requirement, and it<br>
  35. * should be up to the developer and/or the IT department to decide what is appropriate and what not.<br>
  36. *<br>
  37. * @module crdtuxp
  38. * @namespace crdtuxp
  39. */
  40. const DEFAULT_WAIT_FILE_INTERVAL_MILLISECONDS = 1000;
  41. const DEFAULT_WAIT_FILE_TIMEOUT_MILLISECONDS = 60000;
  42. const RESPONSE_CHECK_FILE_INTERVAL_MILLISECONDS = 500;
  43. const RESPONSE_CHECK_FILE_TIMEOUT_MILLISECONDS = 1000;
  44. const UXP_VARIANT_PHOTOSHOP_UXP = "UXP_VARIANT_PHOTOSHOP_UXP";
  45. const UXP_VARIANT_PHOTOSHOP_UXPSCRIPT = "UXP_VARIANT_PHOTOSHOP_UXPSCRIPT";
  46. const UXP_VARIANT_INDESIGN_UXP = "UXP_VARIANT_INDESIGN_UXP";
  47. const UXP_VARIANT_INDESIGN_UXPSCRIPT = "UXP_VARIANT_INDESIGN_UXPSCRIPT";
  48. const UXP_VARIANT_INDESIGN_SERVER_UXPSCRIPT = "UXP_VARIANT_INDESIGN_SERVER_UXPSCRIPT";
  49. const FILE_NAME_EXTENSION_JSON = "json";
  50. const FILE_NAME_SUFFIX_TQL_REQUEST = "q";
  51. const FILE_NAME_SUFFIX_TQL_RESPONSE = "r";
  52. const LENGTH_REQUEST_ID = 10;
  53. const RESOLVED_PROMISE_UNDEFINED = Promise.resolve(undefined);
  54. const RESOLVED_PROMISE_FALSE = Promise.resolve(false);
  55. const RESOLVED_PROMISE_TRUE = Promise.resolve(true);
  56. function getPlatformGlobals() {
  57. return global;
  58. }
  59. let platformGlobals = getPlatformGlobals();
  60. platformGlobals.getPlatformGlobals = getPlatformGlobals;
  61. platformGlobals.defineGlobalObject = function defineGlobalObject(globalName) {
  62. if (! platformGlobals[globalName]) {
  63. platformGlobals[globalName] = {};
  64. }
  65. return platformGlobals[globalName];
  66. }
  67. /**
  68. * <code>localhost.tgrg.net</code> resolves to <code>127.0.0.1</code><br>
  69. * <br>
  70. * The Tightener daemon manages the necessary certificate for https
  71. *
  72. * @constant {string} DNS_NAME_FOR_LOCALHOST
  73. */
  74. const DNS_NAME_FOR_LOCALHOST = "localhost.tgrg.net";
  75. /**
  76. * The Tightener daemon listens for HTTPS connections on port <code>18888</code>.
  77. *
  78. * @constant {number} PORT_TIGHTENER_DAEMON
  79. */
  80. const PORT_TIGHTENER_DAEMON = 18888;
  81. const LOCALHOST_URL = "https://" + DNS_NAME_FOR_LOCALHOST+ ":" + PORT_TIGHTENER_DAEMON;
  82. /**
  83. * The Tightener daemon provides persistent named scopes (similar to persistent ExtendScript engines).<br>
  84. * <br>
  85. * When executing multiple TQL scripts in succession a named scope will retain any globals that<br>
  86. * were defined by a previous script.
  87. *
  88. * @constant {string} TQL_SCOPE_NAME_DEFAULT
  89. */
  90. const TQL_SCOPE_NAME_DEFAULT = "defaultScope";
  91. const PLATFORM_MAC_OS_X = "darwin";
  92. if (! module.exports) {
  93. module.exports = {};
  94. }
  95. let crdtuxp = module.exports;
  96. module.exports.IS_MAC = require('os').platform() == PLATFORM_MAC_OS_X;
  97. module.exports.IS_WINDOWS = ! module.exports.IS_MAC;
  98. let FILE_NOT_EXIST_ERROR;
  99. if (module.exports.IS_MAC) {
  100. FILE_NOT_EXIST_ERROR = -2;
  101. }
  102. else {
  103. FILE_NOT_EXIST_ERROR = -4058;
  104. }
  105. /**
  106. * @namespace path
  107. * @memberof crdtuxp
  108. */
  109. module.exports.path = {};
  110. if (module.exports.IS_MAC) {
  111. module.exports.path.SEPARATOR = "/";
  112. module.exports.path.OTHER_PLATFORM_SEPARATOR = "\\";
  113. }
  114. else {
  115. module.exports.path.SEPARATOR = "\\";
  116. module.exports.path.OTHER_PLATFORM_SEPARATOR = "/";
  117. }
  118. /**
  119. * Setting log level to <code>crdtuxp.LOG_LEVEL_OFF</code> causes all log output to be suppressed.
  120. *
  121. * @constant {number} LOG_LEVEL_OFF
  122. *
  123. */
  124. const LOG_LEVEL_OFF = 0;
  125. module.exports.LOG_LEVEL_OFF = LOG_LEVEL_OFF;
  126. /**
  127. * Setting log level to <code>crdtuxp.LOG_LEVEL_ERROR</code> causes all log output to be suppressed,<br>
  128. * except for errors.
  129. *
  130. * @constant {number} LOG_LEVEL_ERROR
  131. */
  132. const LOG_LEVEL_ERROR = 1;
  133. module.exports.LOG_LEVEL_ERROR = LOG_LEVEL_ERROR;
  134. /**
  135. * Setting log level to <code>crdtuxp.LOG_LEVEL_WARNING</code> causes all log output to be suppressed,<br>
  136. * except for errors and warnings.
  137. *
  138. * @constant {number} LOG_LEVEL_WARNING
  139. */
  140. const LOG_LEVEL_WARNING = 2;
  141. module.exports.LOG_LEVEL_WARNING = LOG_LEVEL_WARNING;
  142. /**
  143. * Setting log level to <code>crdtuxp.LOG_LEVEL_NOTE</code> causes all log output to be suppressed,<br>
  144. * except for errors, warnings and notes.
  145. *
  146. * @constant {number} LOG_LEVEL_NOTE
  147. */
  148. const LOG_LEVEL_NOTE = 3;
  149. module.exports.LOG_LEVEL_NOTE = LOG_LEVEL_NOTE;
  150. /**
  151. * Setting log level to <code>crdtuxp.LOG_LEVEL_TRACE</code> causes all log output to be output.
  152. *
  153. * @constant {number} LOG_LEVEL_TRACE
  154. */
  155. const LOG_LEVEL_TRACE = 4;
  156. module.exports.LOG_LEVEL_TRACE = LOG_LEVEL_TRACE;
  157. // Symbolic params to <code>getDir()</code>
  158. /**
  159. * Pass <code>crdtuxp.DESKTOP_DIR</code> into <code>crdtuxp.getDir()</code> to get the path of the user's Desktop folder.
  160. *
  161. * @constant {string} DESKTOP_DIR
  162. */
  163. module.exports.DESKTOP_DIR = "DESKTOP_DIR";
  164. /**
  165. * Pass <code>crdtuxp.DOCUMENTS_DIR</code> into <code>crdtuxp.getDir()</code> to get the path of the user's Documents folder.
  166. *
  167. * @constant {string} DOCUMENTS_DIR
  168. */
  169. module.exports.DOCUMENTS_DIR = "DOCUMENTS_DIR";
  170. /**
  171. * Pass <code>crdtuxp.HOME_DIR</code> into <code>crdtuxp.getDir()</code> to get the path of the user's home folder.
  172. *
  173. * @constant {string} HOME_DIR
  174. */
  175. module.exports.HOME_DIR = "HOME_DIR";
  176. /**
  177. * Pass <code>crdtuxp.LOG_DIR</code> into <code>crdtuxp.getDir()</code> to get the path of the Tightener logging folder.
  178. *
  179. * @constant {string} LOG_DIR
  180. */
  181. module.exports.LOG_DIR = "LOG_DIR";
  182. /**
  183. * Pass <code>crdtuxp.SYSTEMDATA_DIR</code> into <code>crdtuxp.getDir()</code> to get the path of the system data folder<br>
  184. * (<code>%PROGRAMDATA%</code> or <code>/Library/Application Support</code>).
  185. *
  186. * @constant {string} SYSTEMDATA_DIR
  187. */
  188. module.exports.SYSTEMDATA_DIR = "SYSTEMDATA_DIR";
  189. /**
  190. * Pass <code>crdtuxp.TMP_DIR</code> into <code>crdtuxp.getDir()</code> to get the path of the temporary folder.
  191. *
  192. * @constant {string} TMP_DIR
  193. */
  194. module.exports.TMP_DIR = "TMP_DIR";
  195. /**
  196. * Pass <code>crdtuxp.USERDATA_DIR</code> into <code>crdtuxp.getDir()</code> to get the path to the user data folder<br>
  197. * (<code>%APPDATA%</code> or <code>~/Library/Application Support</code>).
  198. *
  199. * @constant {string} USERDATA_DIR
  200. */
  201. module.exports.USERDATA_DIR = "USERDATA_DIR";
  202. /**
  203. * <code>crdtuxp.UNIT_NAME_NONE</code> represents unit-less values.
  204. */
  205. module.exports.UNIT_NAME_NONE = "NONE";
  206. /**
  207. * <code>crdtuxp.UNIT_NAME_INCH</code> for inches.
  208. */
  209. module.exports.UNIT_NAME_INCH = "\"";
  210. /**
  211. * <code>crdtuxp.UNIT_NAME_CM</code> for centimeters
  212. */
  213. module.exports.UNIT_NAME_CM = "cm";
  214. /**
  215. * <code>crdtuxp.UNIT_NAME_MM</code> for millimeters
  216. */
  217. module.exports.UNIT_NAME_MM = "mm";
  218. /**
  219. * <code>crdtuxp.UNIT_NAME_CICERO</code> for ciceros
  220. */
  221. module.exports.UNIT_NAME_CICERO = "cicero";
  222. /**
  223. * <code>crdtuxp.UNIT_NAME_PICA</code> for picas
  224. */
  225. module.exports.UNIT_NAME_PICA = "pica";
  226. /**
  227. * <code>crdtuxp.UNIT_NAME_PIXEL</code> for pixels
  228. */
  229. module.exports.UNIT_NAME_PIXEL = "px";
  230. /**
  231. * <code>crdtuxp.UNIT_NAME_POINT</code> for points
  232. */
  233. module.exports.UNIT_NAME_POINT = "pt";
  234. // INI parser states
  235. const STATE_IDLE = 0;
  236. const STATE_SEEN_OPEN_SQUARE_BRACKET = 1;
  237. const STATE_SEEN_NON_WHITE = 2;
  238. const STATE_AFTER_NON_WHITE = 3;
  239. const STATE_SEEN_EQUAL = 4;
  240. const STATE_ERROR = 5;
  241. const STATE_SEEN_CLOSE_SQUARE_BRACKET = 6;
  242. const STATE_IN_COMMENT = 7;
  243. // INI value string processing helpers
  244. const REGEXP_TRIM = /^\s*(\S?.*?)\s*$/;
  245. const REGEXP_TRIM_REPLACE = "$1";
  246. const REGEXP_DESPACE = /\s+/g;
  247. const REGEXP_DESPACE_REPLACE = "";
  248. const REGEXP_ALPHA_ONLY = /[^-a-zA-Z0-9$]+/g;
  249. const REGEXP_ALPHA_ONLY_REPLACE = "";
  250. const REGEXP_SECTION_NAME_ONLY = /[^-a-zA-Z0-9$:]+/g;
  251. const REGEXP_SECTION_NAME_ONLY_REPLACE = "";
  252. const REGEXP_NUMBER_ONLY = /^([\d\.]+).*$/;
  253. const REGEXP_NUMBER_ONLY_REPLACE = "$1";
  254. const REGEXP_UNIT_ONLY = /^[\d\.]+\s*(.*)$/;
  255. const REGEXP_UNIT_ONLY_REPLACE = "$1";
  256. const REGEXP_PICAS = /^([\d]+)p(([\d]*)(\.([\d]+)?)?)?$/;
  257. const REGEXP_PICAS_REPLACE = "$1";
  258. const REGEXP_PICAS_POINTS_REPLACE = "$2";
  259. const REGEXP_CICEROS = /^([\d]+)c(([\d]*)(\.([\d]+)?)?)?$/;
  260. const REGEXP_CICEROS_REPLACE = "$1";
  261. const REGEXP_CICEROS_POINTS_REPLACE = "$2";
  262. const LOCALE_EN_US = "en_US";
  263. const DEFAULT_LOCALE = LOCALE_EN_US;
  264. const BTN_OK = "BTN_OK";
  265. const TTL_DIALOG_ALERT = "TTL_DIALOG_ALERT";
  266. let LOCALE_STRINGS = {
  267. BTN_OK: {
  268. "en_US": "OK"
  269. },
  270. TTL_DIALOG_ALERT: {
  271. "en_US": "Alert"
  272. }
  273. };
  274. module.exports.LOCALE = DEFAULT_LOCALE;
  275. module.exports.LOCALE_STRINGS = LOCALE_STRINGS;
  276. module.exports.LOCALE_EN_US = LOCALE_EN_US;
  277. //
  278. // UXP internally caches responses from the server - we need to avoid this as each script
  279. // run can return different results. <code>HTTP_CACHE_BUSTER</code> will be incremented after each use.
  280. //
  281. let HTTP_CACHE_BUSTER = Math.floor(Math.random() * 1000000);
  282. let LOG_LEVEL_STACK = [];
  283. let LOG_ENTRY_EXIT = false;
  284. let LOG_LEVEL = LOG_LEVEL_OFF;
  285. let IN_LOGGER = false;
  286. let LOG_TO_UXPDEVTOOL_CONSOLE = true;
  287. let LOG_TO_CRDT = false;
  288. let LOG_TO_FILE_PATH = undefined;
  289. // Inefficient logging using readSync/writeSync
  290. let SYNC_LOG_TO_FILE_PATH = undefined;
  291. // Set to false to suppress calls to consoleLog
  292. let LOG_TO_CONSOLE = true;
  293. let SYS_INFO;
  294. /**
  295. * Make sure a path ends in a trailing separator (helps identify directory paths)
  296. *
  297. * @function addTrailingSeparator
  298. * @memberof crdtuxp.path
  299. *
  300. * @param {string} filePath - a file path
  301. * @param {string=} separator - the separator to use. If omitted, will try to guess the separator.
  302. * @returns file path with a terminating separator
  303. */
  304. function addTrailingSeparator(filePath, separator) {
  305. // coderstate: function
  306. let retVal = filePath;
  307. do {
  308. try {
  309. if (! filePath) {
  310. break;
  311. }
  312. const lastChar = filePath.substr(-1);
  313. if (
  314. lastChar == crdtuxp.path.SEPARATOR
  315. ||
  316. lastChar == crdtuxp.path.OTHER_PLATFORM_SEPARATOR
  317. ) {
  318. break;
  319. }
  320. if (! separator) {
  321. separator = crdtuxp.path.SEPARATOR;
  322. }
  323. retVal += separator;
  324. }
  325. catch (err) {
  326. crdtuxp.logError(arguments, "throws " + err);
  327. }
  328. }
  329. while (false);
  330. return retVal;
  331. }
  332. module.exports.path.addTrailingSeparator = addTrailingSeparator;
  333. /**
  334. * Show an alert.
  335. *
  336. * @function alert
  337. * @memberof crdtuxp
  338. *
  339. * @param {string} message - string to display
  340. * @returns {Promise<any>}
  341. */
  342. function alert(message) {
  343. // coderstate: promisor
  344. let retVal = RESOLVED_PROMISE_UNDEFINED;
  345. do {
  346. try {
  347. var uxpContext = getUXPContext();
  348. if (uxpContext.uxpVariant == UXP_VARIANT_INDESIGN_SERVER_UXPSCRIPT) {
  349. // We've lost access to the alert() function in InDesign Server, which writes
  350. // to stdout.
  351. // The only workaround I currently have is to pass through ExtendScript
  352. uxpContext.app.doScript(
  353. "alert(" + crdtuxp.dQ(message) + ")",
  354. uxpContext.indesign.ScriptLanguage.JAVASCRIPT);
  355. retVal = RESOLVED_PROMISE_TRUE;
  356. break;
  357. }
  358. if (uxpContext.uxpVariant == UXP_VARIANT_INDESIGN_UXPSCRIPT) {
  359. // InDesign dialogs are not async - they stall the thread until they
  360. // are closed
  361. const dlg = uxpContext.app.dialogs.add();
  362. const col = dlg.dialogColumns.add();
  363. const stText = col.staticTexts.add();
  364. stText.staticLabel = "" + message;
  365. dlg.canCancel = false;
  366. dlg.show();
  367. dlg.destroy();
  368. retVal = RESOLVED_PROMISE_TRUE;
  369. break;
  370. }
  371. if (
  372. uxpContext.uxpVariant == UXP_VARIANT_PHOTOSHOP_UXP
  373. ||
  374. uxpContext.uxpVariant == UXP_VARIANT_PHOTOSHOP_UXPSCRIPT
  375. ) {
  376. function modalDialog() {
  377. const dlg = document.createElement("dialog");
  378. const frm = document.createElement("form");
  379. const bdy = document.createElement("sp-body");
  380. bdy.textContent = message;
  381. frm.appendChild(bdy);
  382. const buttonContainer = document.createElement("div");
  383. buttonContainer.style.display = "flex";
  384. buttonContainer.style.justifyContent = "flex-end";
  385. frm.appendChild(buttonContainer);
  386. const btnOK = document.createElement("sp-button");
  387. buttonContainer.appendChild(btnOK);
  388. btnOK.textContent = S(BTN_OK);
  389. btnOK.onclick = function onClick() {
  390. dlg.close();
  391. };
  392. dlg.appendChild(frm);
  393. document.body.appendChild(dlg);
  394. return dlg.uxpShowModal(
  395. {
  396. title: S(TTL_DIALOG_ALERT),
  397. resize: "none",
  398. size: { width: 400, height: 100}
  399. }
  400. );
  401. }
  402. function executeAsModalResolveFtn() {
  403. // coderstate: resolver
  404. return true;
  405. };
  406. function executeAsModalRejectFtn(reason) {
  407. // coderstate: rejector
  408. crdtuxp.logError(arguments, "rejected for " + reason);
  409. return undefined;
  410. };
  411. retVal =
  412. uxpContext.photoshop.core.executeAsModal(
  413. modalDialog,
  414. {
  415. "commandName": "alert message"
  416. }
  417. ).then(
  418. executeAsModalResolveFtn,
  419. executeAsModalRejectFtn);
  420. break;
  421. }
  422. }
  423. catch (err) {
  424. crdtuxp.logError(arguments, "throws " + err);
  425. }
  426. }
  427. while (false);
  428. return retVal;
  429. }
  430. module.exports.alert = alert;
  431. /**
  432. * Decode a string that was encoded using base64.<br>
  433. * <br>
  434. * The evalTQL variant of the function has not been speed-tested; it's mainly for testing things.<br>
  435. * <br>
  436. * I suspect it might only be beneficial for very large long strings, if that.<br>
  437. * The overheads might be larger than the speed benefit.
  438. *
  439. * @function base64decode
  440. * @memberof crdtuxp
  441. *
  442. * @param {string} base64Str - base64 encoded string
  443. * @param {object=} options - options: {<br>
  444. * isBinary: true/false, default false<br>
  445. * }
  446. * @returns {Promise<string|array|undefined>} decoded string
  447. */
  448. function base64decode(base64Str, options) {
  449. // coderstate: promisor
  450. let retVal = RESOLVED_PROMISE_UNDEFINED;
  451. do {
  452. try {
  453. let isBinary = options && options.isBinary;
  454. let context = getContext();
  455. if (! context.IS_FORCE_USE_DAEMON) {
  456. let rawString = window.atob(base64Str);
  457. let byteArray = rawStringToByteArray(rawString);
  458. if (byteArray) {
  459. if (isBinary) {
  460. retVal = Promise.resolve(byteArray);
  461. }
  462. else {
  463. retVal = Promise.resolve(binaryUTF8ToStr(byteArray));
  464. }
  465. }
  466. break;
  467. }
  468. let evalTQLOptions = {
  469. isBinary: isBinary
  470. };
  471. let responsePromise =
  472. evalTQL(
  473. "base64decode(" + dQ(base64Str) + ")",
  474. evalTQLOptions
  475. );
  476. if (! responsePromise) {
  477. break;
  478. }
  479. function evalTQLResolveFtn(response) {
  480. // coderstate: resolver
  481. let retVal;
  482. do {
  483. if (! response || response.error) {
  484. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  485. break;
  486. }
  487. if (isBinary) {
  488. retVal = deQuote(response.text);
  489. }
  490. else {
  491. retVal = response.text;
  492. }
  493. }
  494. while (false);
  495. return retVal;
  496. };
  497. function evalTQLRejectFtn(reason) {
  498. // coderstate: rejector
  499. crdtuxp.logError(arguments, "rejected for " + reason);
  500. return undefined;
  501. };
  502. retVal = responsePromise.then(
  503. evalTQLResolveFtn,
  504. evalTQLRejectFtn
  505. );
  506. }
  507. catch (err) {
  508. crdtuxp.logError(arguments, "throws " + err);
  509. }
  510. }
  511. while (false);
  512. return retVal;
  513. }
  514. module.exports.base64decode = base64decode;
  515. /**
  516. * Encode a string or an array of bytes using Base 64 encoding.<br>
  517. * <br>
  518. * The evalTQL variant of the function has not been speed-tested; it's mainly for testing things.<br>
  519. * <br>
  520. * I suspect it might only be beneficial for very large long strings, if that.<br>
  521. * <br>
  522. * The overheads might be larger than the speed benefit.
  523. *
  524. * @function base64encode
  525. * @memberof crdtuxp
  526. *
  527. * @param {string} s_or_ByteArr - either a string or an array containing bytes (0-255).
  528. * @returns {Promise<string|undefined>} encoded string
  529. *
  530. */
  531. function base64encode(s_or_ByteArr) {
  532. // coderstate: promisor
  533. let retVal = RESOLVED_PROMISE_UNDEFINED;
  534. do {
  535. try {
  536. let context = getContext();
  537. if (! context.IS_FORCE_USE_DAEMON) {
  538. let byteArray;
  539. if ("string" == typeof s_or_ByteArr) {
  540. byteArray = strToUTF8(s_or_ByteArr);
  541. }
  542. else {
  543. byteArray = s_or_ByteArr;
  544. }
  545. let rawString = byteArrayToRawString(byteArray);
  546. retVal = window.btoa(rawString);
  547. break;
  548. }
  549. const responsePromise =
  550. evalTQL(
  551. "base64encode(" + dQ(s_or_ByteArr) + ")"
  552. );
  553. if (! responsePromise) {
  554. break;
  555. }
  556. function evalTQLResolveFtn(response) {
  557. // coderstate: resolver
  558. let retVal;
  559. do {
  560. try {
  561. if (! response || response.error) {
  562. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  563. break;
  564. }
  565. retVal = response.text;
  566. }
  567. catch (err) {
  568. crdtuxp.logError(arguments, "throws " + err);
  569. }
  570. }
  571. while (false);
  572. return retVal;
  573. };
  574. function evalTQLRejectFtn(reason) {
  575. // coderstate: rejector
  576. crdtuxp.logError(arguments, "rejected for " + reason);
  577. return undefined;
  578. };
  579. retVal = responsePromise.then(
  580. evalTQLResolveFtn,
  581. evalTQLRejectFtn
  582. );
  583. }
  584. catch (err) {
  585. crdtuxp.logError(arguments, "throws " + err);
  586. }
  587. }
  588. while (false);
  589. return retVal;
  590. }
  591. module.exports.base64encode = base64encode;
  592. /**
  593. * Get the last segment of a path
  594. *
  595. * @function baseName
  596. * @memberof crdtuxp.path
  597. *
  598. * @param {string} filePath - a file path
  599. * @param {string=} separator - the separator to use. If omitted, will try to guess the separator.
  600. * @returns {string} the last segment of the path
  601. */
  602. function baseName(filePath, separator) {
  603. // coderstate: function
  604. let endSegment;
  605. try {
  606. if (! separator) {
  607. separator = crdtuxp.path.SEPARATOR;
  608. }
  609. // toString() handles cases where filePath is not a real string
  610. let splitPath = filePath.toString().split(separator);
  611. do {
  612. endSegment = splitPath.pop();
  613. }
  614. while (splitPath.length > 0 && endSegment == "");
  615. }
  616. catch (err) {
  617. crdtuxp.logError(arguments, "throws " + err);
  618. }
  619. return endSegment;
  620. }
  621. module.exports.path.baseName = baseName;
  622. /**
  623. * Decode an array of bytes that contains a UTF-8 encoded string.
  624. *
  625. * @function binaryUTF8ToStr
  626. * @memberof crdtuxp
  627. *
  628. * @param {array} in_byteArray - an array containing bytes (0-255) for a string using UTF-8 encoding.
  629. * @returns {string|undefined} a string or undefined if the UTF-8 is not valid
  630. */
  631. function binaryUTF8ToStr(in_byteArray) {
  632. // coderstate: function
  633. let retVal = undefined;
  634. try {
  635. let idx = 0;
  636. let len = in_byteArray.length;
  637. let c;
  638. while (idx < len) {
  639. let byte = in_byteArray[idx];
  640. idx++;
  641. let bit7 = byte >> 7;
  642. if (! bit7) {
  643. // U+0000 - U+007F
  644. c = String.fromCharCode(byte);
  645. }
  646. else {
  647. let bit6 = (byte & 0x7F) >> 6;
  648. if (! bit6) {
  649. // Invalid
  650. retVal = undefined;
  651. break;
  652. }
  653. else {
  654. let byte2 = in_byteArray[idx];
  655. idx++;
  656. let bit5 = (byte & 0x3F) >> 5;
  657. if (! bit5) {
  658. // U+0080 - U+07FF
  659. c = String.fromCharCode(((byte & 0x1F) << 6) | (byte2 & 0x3F));
  660. }
  661. else {
  662. let byte3 = in_byteArray[idx];
  663. idx++;
  664. let bit4 = (byte & 0x1F) >> 4;
  665. if (! bit4) {
  666. // U+0800 - U+FFFF
  667. c = String.fromCharCode(
  668. ((byte & 0x0F) << 12) |
  669. ((byte2 & 0x3F) << 6) |
  670. (byte3 & 0x3F)
  671. );
  672. }
  673. else {
  674. // Not handled U+10000 - U+10FFFF
  675. retVal = undefined;
  676. break;
  677. }
  678. }
  679. }
  680. }
  681. if (! retVal) {
  682. retVal = "";
  683. }
  684. retVal += c;
  685. }
  686. }
  687. catch (err) {
  688. crdtuxp.logError(arguments, "throws " + err);
  689. retVal = undefined;
  690. }
  691. return retVal;
  692. }
  693. module.exports.binaryUTF8ToStr = binaryUTF8ToStr;
  694. /**
  695. * Make a byte array into a 'fake string'. Not UTF8-aware
  696. *
  697. * @function byteArrayToRawString
  698. * @memberof crdtuxp
  699. *
  700. * @param {array} in_array - a byte array
  701. * @returns {string|undefined} a string with the exact same bytes
  702. */
  703. function byteArrayToRawString(in_array) {
  704. // coderstate: function
  705. let retVal = "";
  706. try {
  707. for (let idx = 0; idx < in_array.length; idx++) {
  708. retVal += String.fromCharCode(in_array[idx]);
  709. }
  710. }
  711. catch (err) {
  712. crdtuxp.logError(arguments, "throws " + err);
  713. }
  714. return retVal;
  715. }
  716. module.exports.byteArrayToRawString = byteArrayToRawString;
  717. /**
  718. * Internal: convert a Unicode character code to a 1 to 3 byte UTF8 byte sequence
  719. *
  720. * @function charCodeToUTF8__
  721. *
  722. * @param {number} in_charCode - a Unicode character code
  723. * @returns {array} an array with 1 to 3 bytes
  724. */
  725. function charCodeToUTF8__(in_charCode) {
  726. // coderstate: function
  727. let retVal = undefined;
  728. try {
  729. if (in_charCode <= 0x007F) {
  730. retVal = [];
  731. retVal.push(in_charCode);
  732. }
  733. else if (in_charCode <= 0x07FF) {
  734. const hi = 0xC0 + ((in_charCode >> 6) & 0x1F);
  735. const lo = 0x80 + ((in_charCode )& 0x3F);
  736. retVal = [];
  737. retVal.push(hi);
  738. retVal.push(lo);
  739. }
  740. else {
  741. const hi = 0xE0 + ((in_charCode >> 12) & 0x1F);
  742. const mid = 0x80 + ((in_charCode >> 6) & 0x3F);
  743. const lo = 0x80 + ((in_charCode ) & 0x3F);
  744. retVal = [];
  745. retVal.push(hi);
  746. retVal.push(mid);
  747. retVal.push(lo);
  748. }
  749. }
  750. catch (err) {
  751. crdtuxp.logError(arguments, "throws " + err);
  752. // anything weird, we return undefined
  753. retVal = undefined;
  754. }
  755. return retVal;
  756. }
  757. /**
  758. * Configure the logger
  759. *
  760. * @function configLogger
  761. * @memberof crdtuxp
  762. *
  763. * @param {object} logInfo - object with logger setup info<br>
  764. * <code>logLevel: 0-4<br>
  765. * logEntryExit: boolean<br>
  766. * logToUXPConsole: boolean<br>
  767. * logToCRDT: boolean<br>
  768. * logToFilePath: undefined or a file path for logging<br></code>
  769. *
  770. * @returns {boolean} success/failure
  771. */
  772. function configLogger(logInfo) {
  773. // coderstate: function
  774. let retVal = false;
  775. do {
  776. try {
  777. if (! logInfo) {
  778. break;
  779. }
  780. if ("logLevel" in logInfo) {
  781. LOG_LEVEL = logInfo.logLevel;
  782. }
  783. if ("logEntryExit" in logInfo) {
  784. LOG_ENTRY_EXIT = logInfo.logEntryExit;
  785. }
  786. if ("logToUXPConsole" in logInfo) {
  787. LOG_TO_UXPDEVTOOL_CONSOLE = logInfo.logToUXPConsole;
  788. }
  789. if ("logToCRDT" in logInfo) {
  790. LOG_TO_CRDT = logInfo.logToCRDT;
  791. }
  792. if ("logToFilePath" in logInfo) {
  793. LOG_TO_FILE_PATH = logInfo.logToFilePath;
  794. }
  795. if ("syncLogToFilePath" in logInfo) {
  796. SYNC_LOG_TO_FILE_PATH = logInfo.syncLogToFilePath;
  797. }
  798. retVal = true;
  799. }
  800. catch (err) {
  801. consoleLog("configLogger throws " + err);
  802. }
  803. }
  804. while (false);
  805. return retVal;
  806. }
  807. module.exports.configLogger = configLogger;
  808. /**
  809. * Bottleneck for <code>console.log</code>. Only call this function for when <code>crdtuxp.log...</code> is not<br>
  810. * available, e.g. before <code>crdtux</code> has loaded or from within functions used by the logging<br>
  811. * functionaly like <code>crdtuxp.evalTQL()</code><br>
  812. *
  813. * @function consoleLog
  814. * @memberof crdtuxp
  815. *
  816. * @param {...*} args - args for function
  817. */
  818. function consoleLog(...args) {
  819. // coderstate: function
  820. if (LOG_TO_CONSOLE) {
  821. console.log(...args);
  822. }
  823. if (SYNC_LOG_TO_FILE_PATH) {
  824. fileAppend_(SYNC_LOG_TO_FILE_PATH, args[0] + "\n");
  825. }
  826. }
  827. module.exports.consoleLog = consoleLog;
  828. /**
  829. * Reverse the operation of the <code>crdtuxp.encrypt()</code> function.<br>
  830. * <br>
  831. * Only available to paid developer accounts
  832. *
  833. * @function decrypt
  834. * @memberof crdtuxp
  835. *
  836. * @param {string} s_or_ByteArr - a string or an array of bytes
  837. * @param {string} aesKey - a string or an array of bytes
  838. * @returns {Promise<Array|undefined>} an array of bytes
  839. */
  840. function decrypt(s_or_ByteArr, aesKey, aesIV) {
  841. // coderstate: promisor
  842. let retVal = RESOLVED_PROMISE_UNDEFINED;
  843. do {
  844. try {
  845. if (! aesIV) {
  846. aesIV = "";
  847. }
  848. const responsePromise =
  849. evalTQL(
  850. "decrypt(" +
  851. dQ(s_or_ByteArr) + ", " +
  852. dQ(aesKey) + ", " +
  853. dQ(aesIV) +
  854. ")"
  855. );
  856. if (! responsePromise) {
  857. break;
  858. }
  859. function evalTQLResolveFtn(response) {
  860. // coderstate: resolver
  861. let retVal;
  862. do {
  863. if (! response || response.error) {
  864. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  865. break;
  866. }
  867. retVal = response.text;
  868. }
  869. while (false);
  870. return retVal;
  871. };
  872. function evalTQLRejectFtn(reason) {
  873. // coderstate: rejector
  874. crdtuxp.logError(arguments, "rejected for " + reason);
  875. return undefined;
  876. };
  877. retVal = responsePromise.then(
  878. evalTQLResolveFtn,
  879. evalTQLRejectFtn
  880. );
  881. }
  882. catch (err) {
  883. crdtuxp.logError(arguments, "throws " + err);
  884. }
  885. }
  886. while (false);
  887. return retVal;
  888. }
  889. module.exports.decrypt = decrypt;
  890. /**
  891. * Delayed execution of a function
  892. *
  893. * @function delayFunction
  894. * @memberof crdtuxp
  895. *
  896. * @param {number} delayTimeMilliseconds - a delay in milliseconds
  897. * @param {function} ftn - a function
  898. * @param {...*} args - optional args for function
  899. * @returns {Promise<any>}
  900. */
  901. function delayFunction(delayTimeMilliseconds, ftn, ...args) {
  902. // coderstate: promisor
  903. let retVal = RESOLVED_PROMISE_UNDEFINED;
  904. try {
  905. function executor(resolveFtn, rejectFtn) {
  906. // coderstate: executor
  907. function timeoutFtn() {
  908. // coderstate: executor
  909. try {
  910. let result = ftn(...args);
  911. if (result instanceof Promise) {
  912. result.then(
  913. resolveFtn,
  914. rejectFtn
  915. );
  916. }
  917. else {
  918. resolveFtn(result);
  919. }
  920. }
  921. catch (err) {
  922. rejectFtn(err);
  923. }
  924. };
  925. setTimeout(
  926. timeoutFtn,
  927. delayTimeMilliseconds
  928. );
  929. };
  930. retVal = new Promise(executor);
  931. }
  932. catch (err) {
  933. crdtuxp.logError(arguments, "throws " + err);
  934. }
  935. return retVal;
  936. }
  937. module.exports.delayFunction = delayFunction;
  938. /**
  939. * Reverse the operation of <code>crdtuxp.dQ()</code> or <code>crdtuxp.sQ()</code>.
  940. *
  941. * @function deQuote
  942. * @memberof crdtuxp
  943. *
  944. * @param {string} quotedString - a quoted string
  945. * @returns {array} a byte array. If the quoted string contains any <code>\uHHHH</code> codes,<br>
  946. * these are first re-encoded using UTF-8 before storing them into the byte array.
  947. */
  948. function deQuote(quotedString) {
  949. // coderstate: function
  950. let retVal = [];
  951. let state = -1;
  952. let buffer = [];
  953. do {
  954. try {
  955. let qLen = quotedString.length;
  956. if (qLen < 2) {
  957. retVal = strToUTF8(quotedString);
  958. break;
  959. }
  960. const quoteChar = quotedString.charAt(0);
  961. qLen -= 1;
  962. if (quoteChar != quotedString.charAt(qLen)) {
  963. retVal = strToUTF8(quotedString);
  964. break;
  965. }
  966. if (quoteChar != '"' && quoteChar != "'") {
  967. retVal = strToUTF8(quotedString);
  968. break;
  969. }
  970. state = 0;
  971. let cCode = 0;
  972. for (let charIdx = 1; charIdx < qLen; charIdx++) {
  973. if (state == -1) {
  974. break;
  975. }
  976. const c = quotedString.charAt(charIdx);
  977. switch (state) {
  978. case 0:
  979. if (c == '\\') {
  980. state = 1;
  981. }
  982. else {
  983. buffer.push(c.charCodeAt(0));
  984. }
  985. break;
  986. case 1:
  987. if (c == 'x') {
  988. // state 2->3->0
  989. state = 2;
  990. }
  991. else if (c == 'u') {
  992. // state 4->5->6->7->0
  993. state = 4;
  994. }
  995. else if (c == 't') {
  996. buffer.push(0x09);
  997. state = 0;
  998. }
  999. else if (c == 'r') {
  1000. buffer.push(0x0D);
  1001. state = 0;
  1002. }
  1003. else if (c == 'n') {
  1004. buffer.push(0x0A);
  1005. state = 0;
  1006. }
  1007. else {
  1008. buffer.push(c.charCodeAt(0));
  1009. state = 0;
  1010. }
  1011. break;
  1012. case 2:
  1013. case 4:
  1014. if (c >= '0' && c <= '9') {
  1015. cCode = c.charCodeAt(0) - 0x30;
  1016. state++;
  1017. }
  1018. else if (c >= 'A' && c <= 'F') {
  1019. cCode = c.charCodeAt(0) + 10 - 0x41;
  1020. state++;
  1021. }
  1022. else if (c >= 'a' && c <= 'f') {
  1023. cCode = c.charCodeAt(0) + 10 - 0x61;
  1024. state++;
  1025. }
  1026. else {
  1027. state = -1;
  1028. }
  1029. break;
  1030. case 3:
  1031. case 5:
  1032. case 6:
  1033. case 7:
  1034. if (c >= '0' && c <= '9') {
  1035. cCode = (cCode << 4) + c.charCodeAt(0) - 0x30;
  1036. }
  1037. else if (c >= 'A' && c <= 'F') {
  1038. cCode = (cCode << 4) + c.charCodeAt(0) + 10 - 0x41;
  1039. }
  1040. else if (c >= 'a' && c <= 'f') {
  1041. cCode = (cCode << 4) + c.charCodeAt(0) + 10 - 0x61;
  1042. }
  1043. else {
  1044. state = -1;
  1045. }
  1046. if (state == 3) {
  1047. // Done with \xHH
  1048. buffer.push(cCode);
  1049. state = 0;
  1050. }
  1051. else if (state == 7) {
  1052. // Done with \uHHHHH - convert using UTF-8
  1053. let bytes = charCodeToUTF8__(cCode);
  1054. if (! bytes) {
  1055. state = -1
  1056. }
  1057. else {
  1058. for (let byteIdx = 0; byteIdx < bytes.length; byteIdx++) {
  1059. buffer.push(bytes[byteIdx]);
  1060. }
  1061. state = 0;
  1062. }
  1063. }
  1064. else {
  1065. // Next state: 2->3, 4->5->6->7
  1066. state++;
  1067. }
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. catch (err) {
  1073. crdtuxp.logError(arguments, "throws " + err);
  1074. }
  1075. }
  1076. while (false);
  1077. if (state == 0) {
  1078. retVal = buffer;
  1079. }
  1080. return retVal;
  1081. }
  1082. module.exports.deQuote = deQuote;
  1083. /**
  1084. * Create a directory.<br>
  1085. * <br>
  1086. * Not restricted by the UXP security sandbox.
  1087. *
  1088. * @function dirCreate
  1089. * @memberof crdtuxp
  1090. *
  1091. * @param {string} filePath
  1092. * @returns {Promise<boolean|undefined>} success or failure
  1093. */
  1094. function dirCreate(filePath) {
  1095. // coderstate: promisor
  1096. let retVal = RESOLVED_PROMISE_UNDEFINED;
  1097. do {
  1098. try {
  1099. let context = getContext();
  1100. let uxpContext = getUXPContext();
  1101. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  1102. let parentPath = crdtuxp.path.dirName(filePath);
  1103. let baseName = crdtuxp.path.baseName(filePath);
  1104. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  1105. try {
  1106. const stats = uxpContext.fs.lstatSync(parentPath);
  1107. if (! stats || ! stats.isDirectory()) {
  1108. retVal = RESOLVED_PROMISE_FALSE;
  1109. break;
  1110. }
  1111. }
  1112. catch (err) {
  1113. if (err != FILE_NOT_EXIST_ERROR) {
  1114. crdtuxp.logNote(arguments, "throws " + err);
  1115. }
  1116. break;
  1117. }
  1118. try {
  1119. const stats = uxpContext.fs.lstatSync(filePath);
  1120. if (stats) {
  1121. retVal = RESOLVED_PROMISE_FALSE;
  1122. break;
  1123. }
  1124. }
  1125. catch (err) {
  1126. if (err != FILE_NOT_EXIST_ERROR) {
  1127. crdtuxp.logNote(arguments, "throws " + err);
  1128. }
  1129. }
  1130. try {
  1131. function mkdirResolveFtn() {
  1132. // coderstate: resolver
  1133. return true;
  1134. };
  1135. function mkdirRejectFtn(reason) {
  1136. // coderstate: rejector
  1137. crdtuxp.logError(arguments, "rejected for " + reason);
  1138. return false;
  1139. };
  1140. // If no callback given, returns a Promise
  1141. retVal = uxpContext.fs.mkdir(filePath).then(
  1142. mkdirResolveFtn,
  1143. mkdirRejectFtn
  1144. );
  1145. }
  1146. catch (err) {
  1147. crdtuxp.logError(arguments, "throws " + err);
  1148. }
  1149. break;
  1150. }
  1151. const responsePromise =
  1152. evalTQL(
  1153. "dirCreate(" + dQ(filePath) + ") ? \"true\" : \"false\""
  1154. );
  1155. if (! responsePromise) {
  1156. break;
  1157. }
  1158. function evalTQLResolveFtn(response) {
  1159. // coderstate: resolver
  1160. let retVal;
  1161. do {
  1162. if (! response || response.error) {
  1163. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  1164. break;
  1165. }
  1166. retVal = response.text == "true";
  1167. }
  1168. while (false);
  1169. return retVal;
  1170. };
  1171. function evalTQLRejectFtn(reason) {
  1172. // coderstate: rejector
  1173. crdtuxp.logError(arguments, "rejected for " + reason);
  1174. return undefined;
  1175. };
  1176. retVal = responsePromise.then(
  1177. evalTQLResolveFtn,
  1178. evalTQLRejectFtn
  1179. );
  1180. }
  1181. catch (err) {
  1182. crdtuxp.logError(arguments, "throws " + err);
  1183. }
  1184. }
  1185. while (false);
  1186. return retVal;
  1187. }
  1188. module.exports.dirCreate = dirCreate;
  1189. /**
  1190. * Delete a directory.<br>
  1191. * <br>
  1192. * Not restricted by the UXP security sandbox.<br>
  1193. * <br>
  1194. * Be very careful with the <code>recurse</code> parameter! It is very easy to delete the wrong directory.
  1195. *
  1196. * @function dirDelete
  1197. * @memberof crdtuxp
  1198. *
  1199. * @param {string} filePath
  1200. * @param {boolean} recurse
  1201. * @returns {Promise<boolean|undefined>} success or failure
  1202. */
  1203. function dirDelete(filePath, recurse) {
  1204. // coderstate: promisor
  1205. let retVal = RESOLVED_PROMISE_UNDEFINED;
  1206. do {
  1207. try {
  1208. let context = getContext();
  1209. let uxpContext = getUXPContext();
  1210. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  1211. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  1212. try {
  1213. const stats = uxpContext.fs.lstatSync(filePath);
  1214. if (! stats || ! stats.isDirectory()) {
  1215. retVal = RESOLVED_PROMISE_FALSE;
  1216. break;
  1217. }
  1218. }
  1219. catch (err) {
  1220. if (err != FILE_NOT_EXIST_ERROR) {
  1221. crdtuxp.logNote(arguments, "throws " + err);
  1222. }
  1223. retVal = RESOLVED_PROMISE_FALSE;
  1224. break;
  1225. }
  1226. let entries = [];
  1227. try {
  1228. entries = uxpContext.fs.readdirSync(filePath);
  1229. }
  1230. catch (err) {
  1231. crdtuxp.logError(arguments, "throws " + err);
  1232. retVal = RESOLVED_PROMISE_FALSE;
  1233. break;
  1234. }
  1235. if (! recurse) {
  1236. if (entries.length > 0) {
  1237. retVal = RESOLVED_PROMISE_FALSE;
  1238. break;
  1239. }
  1240. try {
  1241. function rmdirResolveFtn() {
  1242. // coderstate: resolver
  1243. return true;
  1244. };
  1245. function rmdirRejectFtn(reason) {
  1246. // coderstate: rejector
  1247. crdtuxp.logError(arguments, "rejected for " + reason);
  1248. return false;
  1249. };
  1250. // If no callback given, returns a Promise
  1251. retVal = uxpContext.fs.rmdir(filePath).then(
  1252. rmdirResolveFtn,
  1253. rmdirRejectFtn
  1254. );
  1255. }
  1256. catch (err) {
  1257. crdtuxp.logError(arguments, "throws " + err);
  1258. retVal = RESOLVED_PROMISE_FALSE;
  1259. }
  1260. break;
  1261. }
  1262. const dirPathPrefix = addTrailingSeparator(filePath);
  1263. let promises = [];
  1264. for (let idx = 0; idx < entries.length; idx++) {
  1265. let entryPath = dirPathPrefix + entries[idx];
  1266. try {
  1267. const stats = uxpContext.fs.lstatSync(entryPath);
  1268. if (! stats) {
  1269. promises = undefined;
  1270. break;
  1271. }
  1272. let deletePromise;
  1273. if (stats.isDirectory()) {
  1274. function dirDeleteResolveFtn() {
  1275. // coderstate: resolver
  1276. return true;
  1277. };
  1278. function dirDeleteRejectFtn(reason) {
  1279. // coderstate: rejector
  1280. crdtuxp.logError(arguments, "rejected for " + reason);
  1281. return false;
  1282. };
  1283. deletePromise = dirDelete(entryPath, true).then(
  1284. dirDeleteResolveFtn,
  1285. dirDeleteRejectFtn
  1286. );
  1287. }
  1288. else {
  1289. function fileDeletResolveFtn() {
  1290. // coderstate: resolver
  1291. return true;
  1292. };
  1293. function fileDeleteRejectFtn(reason) {
  1294. // coderstate: rejector
  1295. crdtuxp.logError(arguments, "rejected for " + reason);
  1296. return false;
  1297. };
  1298. // If no callback given, returns a Promise
  1299. deletePromise = uxpContext.fs.unlink(entryPath).then(
  1300. fileDeletResolveFtn,
  1301. fileDeleteRejectFtn
  1302. );
  1303. }
  1304. promises.push(deletePromise);
  1305. }
  1306. catch (err) {
  1307. if (err != FILE_NOT_EXIST_ERROR) {
  1308. crdtuxp.logNote(arguments, "throws " + err);
  1309. }
  1310. promises = undefined;
  1311. break;
  1312. }
  1313. }
  1314. if (! promises) {
  1315. retVal = RESOLVED_PROMISE_FALSE;
  1316. }
  1317. function allResolveFtn() {
  1318. // coderstate: resolver
  1319. try {
  1320. function rmdirResolveFtn() {
  1321. // coderstate: resolver
  1322. return true;
  1323. };
  1324. function rmdirRejectFtn(reason) {
  1325. // coderstate: rejector
  1326. crdtuxp.logError(arguments, "rejected for " + reason);
  1327. return false;
  1328. };
  1329. // If no callback given, returns a Promise
  1330. retVal = uxpContext.fs.rmdir(filePath).then(
  1331. rmdirResolveFtn,
  1332. rmdirRejectFtn
  1333. );
  1334. }
  1335. catch (err) {
  1336. crdtuxp.logError(arguments, "throws " + err);
  1337. retVal = false;
  1338. }
  1339. };
  1340. function allRejectFtn(reason) {
  1341. // coderstate: rejector
  1342. crdtuxp.logError(arguments, "rejected for " + reason);
  1343. return false;
  1344. };
  1345. retVal = Promise.allSettled(promises).then(
  1346. allResolveFtn,
  1347. allRejectFtn
  1348. );
  1349. break;
  1350. }
  1351. const responsePromise =
  1352. evalTQL(
  1353. "dirDelete(" +
  1354. dQ(filePath) +
  1355. "," +
  1356. (recurse ? "true" : "false") +
  1357. ") ? \"true\" : \"false\""
  1358. );
  1359. if (! responsePromise) {
  1360. break;
  1361. }
  1362. function evalTQLResolveFtn(response) {
  1363. // coderstate: resolver
  1364. let retVal;
  1365. do {
  1366. if (! response || response.error) {
  1367. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  1368. break;
  1369. }
  1370. retVal = response.text == "true";
  1371. }
  1372. while (false);
  1373. return retVal;
  1374. };
  1375. function evalTQLRejectFtn(reason) {
  1376. // coderstate: rejector
  1377. crdtuxp.logError(arguments, "rejected for " + reason);
  1378. return undefined;
  1379. };
  1380. retVal = responsePromise.then(
  1381. evalTQLResolveFtn,
  1382. evalTQLRejectFtn
  1383. );
  1384. }
  1385. catch (err) {
  1386. crdtuxp.logError(arguments, "throws " + err);
  1387. }
  1388. }
  1389. while (false);
  1390. return retVal;
  1391. }
  1392. module.exports.dirDelete = dirDelete;
  1393. /**
  1394. * Verify whether a directory exists. Will return <code>false</code> if the path points to a file<br>
  1395. * (instead of a directory).<br>
  1396. * <br>
  1397. * Also see <code>crdtuxp.fileExists()</code>.<br>
  1398. * <br>
  1399. * Not restricted by the UXP security sandbox.
  1400. *
  1401. * @function dirExists
  1402. * @memberof crdtuxp
  1403. *
  1404. * @param {string} dirPath - a path to a directory
  1405. * @returns {Promise<boolean|undefined>} success or failure
  1406. */
  1407. function dirExists(dirPath) {
  1408. // coderstate: promisor
  1409. let retVal = RESOLVED_PROMISE_UNDEFINED;
  1410. do {
  1411. try {
  1412. let context = getContext();
  1413. let uxpContext = getUXPContext();
  1414. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  1415. try {
  1416. const stats = uxpContext.fs.lstatSync(dirPath);
  1417. if (! stats || ! stats.isDirectory()) {
  1418. retVal = RESOLVED_PROMISE_FALSE;
  1419. break;
  1420. }
  1421. }
  1422. catch (err) {
  1423. if (err != FILE_NOT_EXIST_ERROR) {
  1424. crdtuxp.logNote(arguments, "throws " + err);
  1425. }
  1426. retVal = RESOLVED_PROMISE_FALSE;
  1427. break;
  1428. }
  1429. retVal = RESOLVED_PROMISE_TRUE;
  1430. break;
  1431. }
  1432. const responsePromise =
  1433. evalTQL(
  1434. "dirExists(" + dQ(dirPath) + ") ? \"true\" : \"false\""
  1435. );
  1436. if (! responsePromise) {
  1437. break;
  1438. }
  1439. function evalTQLResolveFtn(response) {
  1440. // coderstate: resolver
  1441. let retVal;
  1442. do {
  1443. if (! response || response.error) {
  1444. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  1445. break;
  1446. }
  1447. retVal = response.text == "true";
  1448. }
  1449. while (false);
  1450. return retVal;
  1451. };
  1452. function evalTQLRejectFtn(reason) {
  1453. // coderstate: rejector
  1454. crdtuxp.logError(arguments, "rejected for " + reason);
  1455. return undefined;
  1456. };
  1457. retVal = responsePromise.then(
  1458. evalTQLResolveFtn,
  1459. evalTQLRejectFtn
  1460. );
  1461. }
  1462. catch (err) {
  1463. crdtuxp.logError(arguments, "throws " + err);
  1464. }
  1465. }
  1466. while (false);
  1467. return retVal;
  1468. }
  1469. module.exports.dirExists = dirExists;
  1470. /**
  1471. * Get the parent directory of a path
  1472. *
  1473. * @function dirName
  1474. * @memberof crdtuxp.path
  1475. *
  1476. * @param {string} filePath - a file path
  1477. * @param {object=} options - options:<br>
  1478. * <code>{<br>
  1479. * addTrailingSeparator: true/false, default false,<br>
  1480. * separator: separatorchar. the separator to use. If omitted, will try to guess the <br>
  1481. * separator.<br>
  1482. * }</code>
  1483. * @param {string=} separator -
  1484. * @returns the parent of the path
  1485. */
  1486. function dirName(filePath, options) {
  1487. // coderstate: function
  1488. let retVal;
  1489. try {
  1490. let separator;
  1491. if (options) {
  1492. if (options.separator) {
  1493. separator = options.separator;
  1494. }
  1495. }
  1496. if (! separator) {
  1497. separator = crdtuxp.path.SEPARATOR;
  1498. }
  1499. // toString() handles cases where filePath is not a real string
  1500. let splitPath = filePath.toString().split(separator);
  1501. let endSegment;
  1502. do {
  1503. endSegment = splitPath.pop();
  1504. }
  1505. while (splitPath.length > 0 && endSegment == "");
  1506. retVal = splitPath.join(separator);
  1507. if (options && options.addTrailingSeparator) {
  1508. retVal += separator;
  1509. }
  1510. }
  1511. catch (err) {
  1512. crdtuxp.logError(arguments, "throws " + err);
  1513. }
  1514. return retVal;
  1515. }
  1516. module.exports.path.dirName = dirName;
  1517. /**
  1518. * Scan a directory.<br>
  1519. * <br>
  1520. * Not restricted by the UXP security sandbox.
  1521. *
  1522. * @function dirScan
  1523. * @memberof crdtuxp
  1524. *
  1525. * @param {string} filePath
  1526. * @returns {Promise<Array|undefined>} list of items in directory
  1527. */
  1528. function dirScan(filePath) {
  1529. // coderstate: promisor
  1530. let retVal = RESOLVED_PROMISE_UNDEFINED;
  1531. do {
  1532. try {
  1533. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  1534. let context = getContext();
  1535. let uxpContext = getUXPContext();
  1536. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  1537. let entries = [];
  1538. try {
  1539. entries = uxpContext.fs.readdirSync(filePath);
  1540. }
  1541. catch (err) {
  1542. crdtuxp.logError(arguments, "throws " + err);
  1543. retVal = RESOLVED_PROMISE_FALSE;
  1544. break;
  1545. }
  1546. retVal = Promise.resolve(entries);
  1547. break;
  1548. }
  1549. const responsePromise =
  1550. evalTQL(
  1551. "enquote(dirScan(" + dQ(filePath) + ").toString())"
  1552. );
  1553. if (! responsePromise) {
  1554. break;
  1555. }
  1556. function evalTQLResolveFtn(response) {
  1557. // coderstate: resolver
  1558. let retVal = undefined;
  1559. do {
  1560. if (! response || response.error) {
  1561. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  1562. break;
  1563. }
  1564. const responseText = response.text;
  1565. if (! responseText) {
  1566. crdtuxp.logError(arguments, "no responseText");
  1567. break;
  1568. }
  1569. const deQuotedResponseText = deQuote(responseText);
  1570. if (! deQuotedResponseText) {
  1571. crdtuxp.logError(arguments, "no deQuotedResponseText");
  1572. break;
  1573. }
  1574. const binaryResponse = binaryUTF8ToStr(deQuotedResponseText);
  1575. if (! binaryResponse) {
  1576. crdtuxp.logError(arguments, "no binaryResponse");
  1577. break;
  1578. }
  1579. try {
  1580. retVal = JSON.parse(binaryResponse);
  1581. }
  1582. catch (err) {
  1583. crdtuxp.logError(arguments, "failed to parse JSON " + binaryResponse);
  1584. break;
  1585. }
  1586. }
  1587. while (false);
  1588. return retVal;
  1589. };
  1590. function evalTQLRejectFtn(reason) {
  1591. // coderstate: rejector
  1592. crdtuxp.logError(arguments, "rejected for " + reason);
  1593. return undefined;
  1594. };
  1595. retVal = responsePromise.then(
  1596. evalTQLResolveFtn,
  1597. evalTQLRejectFtn
  1598. );
  1599. }
  1600. catch (err) {
  1601. crdtuxp.logError(arguments, "throws " + err);
  1602. }
  1603. }
  1604. while (false);
  1605. return retVal;
  1606. }
  1607. module.exports.dirScan = dirScan;
  1608. /**
  1609. * Wrap a string or a byte array into double quotes, encoding any binary data as a string.<br>
  1610. * Knows how to handle Unicode characters or binary zeroes.<br>
  1611. * <br>
  1612. * When the input is a string, high Unicode characters are encoded as <code>\uHHHH</code>.<br>
  1613. * <br>
  1614. * When the input is a byte array, all bytes are encoded as characters or as <code>\xHH</code><br>
  1615. * escape sequences.
  1616. *
  1617. * @function dQ
  1618. * @memberof crdtuxp
  1619. *
  1620. * @param {string|Array} s_or_ByteArr - a Unicode string or an array of bytes
  1621. * @returns {string|undefined} a string enclosed in double quotes. This string is pure 7-bit<br>
  1622. * ASCII and can be used into generated script code<br>
  1623. * Example:<br>
  1624. * <code>let script = "a=b(" + crdtuxp.dQ(somedata) + ");";</code>
  1625. */
  1626. function dQ(s_or_ByteArr) {
  1627. // coderstate: function
  1628. let retVal;
  1629. try {
  1630. retVal = enQuote__(s_or_ByteArr, "\"");
  1631. }
  1632. catch (err) {
  1633. crdtuxp.logError(arguments, "throws " + err);
  1634. }
  1635. return retVal;
  1636. }
  1637. module.exports.dQ = dQ;
  1638. /**
  1639. * Encrypt a string or array of bytes using a key. A random salt is added into the mix,<br>
  1640. * so even when passing in the same parameter values, the result will be different every time.<br>
  1641. * <br>
  1642. * Only available to paid developer accounts
  1643. *
  1644. * @function encrypt
  1645. * @memberof crdtuxp
  1646. *
  1647. * @param {string} s_or_ByteArr - a string or an array of bytes
  1648. * @param {string} aesKey - a string or an array of bytes, key
  1649. * @param {string=} aesIV - a string or an array of bytes, initial vector
  1650. * @returns {Promise<string|undefined>} a base-64 encoded encrypted string.
  1651. */
  1652. function encrypt(s_or_ByteArr, aesKey, aesIV) {
  1653. // coderstate: promisor
  1654. let retVal = RESOLVED_PROMISE_UNDEFINED;
  1655. do {
  1656. try {
  1657. if (! aesIV) {
  1658. aesIV = "";
  1659. }
  1660. const responsePromise =
  1661. evalTQL(
  1662. "encrypt(" +
  1663. dQ(s_or_ByteArr) + ", " +
  1664. dQ(aesKey) + ", " +
  1665. dQ(aesIV) +
  1666. ")"
  1667. );
  1668. if (! responsePromise) {
  1669. break;
  1670. }
  1671. function evalTQLResolveFtn(response) {
  1672. // coderstate: resolver
  1673. let retVal;
  1674. do {
  1675. if (! response || response.error) {
  1676. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  1677. break;
  1678. }
  1679. retVal = response.text;
  1680. }
  1681. while (false);
  1682. return retVal;
  1683. };
  1684. function evalTQLRejectFtn(reason) {
  1685. // coderstate: rejector
  1686. crdtuxp.logError(arguments, "rejected for " + reason);
  1687. return undefined;
  1688. };
  1689. retVal = responsePromise.then(
  1690. evalTQLResolveFtn,
  1691. evalTQLRejectFtn
  1692. );
  1693. }
  1694. catch (err) {
  1695. crdtuxp.logError(arguments, "throws " + err);
  1696. }
  1697. }
  1698. while (false);
  1699. return retVal;
  1700. }
  1701. module.exports.encrypt = encrypt;
  1702. /**
  1703. * Internal: Escape and wrap a string in quotes
  1704. *
  1705. * @function enQuote__
  1706. *
  1707. * @param {string|Array} s_or_ByteArr - a string or a byte array
  1708. * @param {string} quoteChar - a string with a single character to use for quoting (<code>"'"</code> or <code>'"'</code>)
  1709. * @returns {string} an string
  1710. */
  1711. function enQuote__(s_or_ByteArr, quoteChar) {
  1712. // coderstate: function
  1713. let retVal = "";
  1714. try {
  1715. const quoteCharCode = quoteChar.charCodeAt(0);
  1716. let isString;
  1717. let byteSequence;
  1718. if (s_or_ByteArr instanceof ArrayBuffer) {
  1719. byteSequence = new Uint8Array(in_byteArray);
  1720. }
  1721. else {
  1722. isString = ("string" == typeof s_or_ByteArr);
  1723. byteSequence = s_or_ByteArr;
  1724. }
  1725. const sLen = byteSequence.length;
  1726. let escapedS = "";
  1727. for (let charIdx = 0; charIdx < sLen; charIdx++) {
  1728. let cCode;
  1729. if (isString) {
  1730. cCode = byteSequence.charCodeAt(charIdx);
  1731. }
  1732. else {
  1733. cCode = byteSequence[charIdx];
  1734. }
  1735. if (cCode == 0x5C) {
  1736. escapedS += '\\\\';
  1737. }
  1738. else if (cCode == quoteCharCode) {
  1739. escapedS += '\\' + quoteChar;
  1740. }
  1741. else if (cCode == 0x0A) {
  1742. escapedS += '\\n';
  1743. }
  1744. else if (cCode == 0x0D) {
  1745. escapedS += '\\r';
  1746. }
  1747. else if (cCode == 0x09) {
  1748. escapedS += '\\t';
  1749. }
  1750. else if (cCode < 32 || cCode == 0x7F || (! isString && cCode >= 0x80)) {
  1751. escapedS += "\\x" + toHex(cCode, 2);
  1752. }
  1753. else if (isString && cCode >= 0x80) {
  1754. escapedS += "\\u" + toHex(cCode, 4);
  1755. }
  1756. else {
  1757. escapedS += String.fromCharCode(cCode);
  1758. }
  1759. }
  1760. retVal = quoteChar + escapedS + quoteChar;
  1761. }
  1762. catch (err) {
  1763. crdtuxp.logError(arguments, "throws " + err);
  1764. }
  1765. return retVal;
  1766. }
  1767. /**
  1768. * Send a TQL script to the daemon and wait for the result
  1769. *
  1770. * @function evalTQL
  1771. * @memberof crdtuxp
  1772. *
  1773. * @param {string} tqlScript - a script to run
  1774. * @param {object=} options - optional. <br>
  1775. * <code>options.wait</code> when <code>false</code> don't wait to resolve, default <code>true</code><br>
  1776. * <code>options.isBinary</code> default <code>false</code><br>
  1777. * <code>options.tqlScopeName</code> default <code>TQL_SCOPE_NAME_DEFAULT</code><br>
  1778. * <code>options.waitFileTimeout</code> default <code>DEFAULT_WAIT_FILE_TIMEOUT_MILLISECONDS</code><br>
  1779. * <code>options.waitFileCheckInterval</code> default <code>DEFAULT_WAIT_FILE_INTERVAL_MILLISECONDS</code><br>
  1780. * or can be decoded as a string
  1781. * @returns {Promise<any>} a string or a byte array
  1782. */
  1783. function evalTQL(tqlScript, options) {
  1784. // coderstate: promisor
  1785. let retVal = Promise.resolve({ error: true });
  1786. do {
  1787. try {
  1788. let context = crdtuxp.getContext();
  1789. let resultIsRawBinary = false;
  1790. let wait = true;
  1791. let tqlScopeName = TQL_SCOPE_NAME_DEFAULT;
  1792. let waitFileTimeout = DEFAULT_WAIT_FILE_TIMEOUT_MILLISECONDS;
  1793. let waitFileCheckInterval = DEFAULT_WAIT_FILE_INTERVAL_MILLISECONDS;
  1794. if (options) {
  1795. resultIsRawBinary = !!options.isBinary;
  1796. wait = options.wait === undefined ? true : options.wait;
  1797. tqlScopeName = options.tqlScopeName || TQL_SCOPE_NAME_DEFAULT;
  1798. waitFileTimeout = options.waitFileTimeout || DEFAULT_WAIT_FILE_TIMEOUT_MILLISECONDS;
  1799. waitFileCheckInterval = options.waitFileCheckInterval || DEFAULT_WAIT_FILE_INTERVAL_MILLISECONDS;
  1800. }
  1801. let uxpContext = getUXPContext();
  1802. if (! uxpContext.hasNetworkAccess && ! uxpContext.hasDirectFileAccess) {
  1803. consoleLog("evalTQL needs direct file access or network access");
  1804. // Need either network access or direct file access - cannot do
  1805. // without
  1806. break;
  1807. }
  1808. if (! uxpContext.hasNetworkAccess || context.IS_FORCE_DAEMON_FILE_BASED_API) {
  1809. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  1810. if (! context?.PATH_EVAL_TQL)
  1811. {
  1812. consoleLog("evalTQL: need context.PATH_EVAL_TQL to be set");
  1813. // Need to know where to put the packet
  1814. break;
  1815. }
  1816. if (! uxpContext.tqlRequestID) {
  1817. uxpContext.tqlRequestID = 0;
  1818. uxpContext.tqlRequestsByID = {};
  1819. }
  1820. let validUntil =
  1821. (new Date()).getTime() + DEFAULT_WAIT_FILE_TIMEOUT_MILLISECONDS;
  1822. let tqlRequest = {
  1823. validUntil: validUntil,
  1824. wait: wait ? 1 : 0,
  1825. sessionID: uxpContext.sessionID,
  1826. requestID: ++uxpContext.tqlRequestID,
  1827. tqlRequest: tqlScript,
  1828. tqlScopeName: tqlScopeName
  1829. };
  1830. uxpContext.tqlRequestsByID[tqlRequest.requestID] = tqlRequest;
  1831. let tqlRequestJSON = JSON.stringify(tqlRequest);
  1832. let tqlRequestByteArray = strToUTF8(tqlRequestJSON);
  1833. let tqlSharedFilePathPrefix =
  1834. context.PATH_EVAL_TQL +
  1835. tqlRequest.sessionID +
  1836. crdtuxp.leftPad(tqlRequest.requestID, "0", LENGTH_REQUEST_ID);
  1837. let requestFilePath =
  1838. tqlSharedFilePathPrefix +
  1839. FILE_NAME_SUFFIX_TQL_REQUEST +
  1840. "." +
  1841. FILE_NAME_EXTENSION_JSON;
  1842. let responseFilePath =
  1843. tqlSharedFilePathPrefix +
  1844. FILE_NAME_SUFFIX_TQL_RESPONSE +
  1845. "." +
  1846. FILE_NAME_EXTENSION_JSON;
  1847. function handleResponseData(replyByteArray) {
  1848. // coderstate: function
  1849. let retVal = undefined;
  1850. let responseText;
  1851. let responseTextUnwrapped;
  1852. do {
  1853. try {
  1854. if (! replyByteArray) {
  1855. break;
  1856. }
  1857. let jsonResponse = binaryUTF8ToStr(replyByteArray);
  1858. if (jsonResponse == "undefined") {
  1859. break;
  1860. }
  1861. let response;
  1862. try {
  1863. response = JSON.parse(jsonResponse);
  1864. }
  1865. catch (err) {
  1866. break;
  1867. }
  1868. if (! response || response.result === undefined) {
  1869. break;
  1870. }
  1871. responseText = response.result;
  1872. }
  1873. catch (err) {
  1874. consoleLog("evalTQL handleResponseData throws " + err);
  1875. break;
  1876. }
  1877. }
  1878. while (false);
  1879. if (resultIsRawBinary) {
  1880. responseTextUnwrapped = responseText;
  1881. }
  1882. else if (responseText) {
  1883. responseTextUnwrapped = binaryUTF8ToStr(deQuote(responseText));
  1884. }
  1885. retVal = {
  1886. text: responseTextUnwrapped
  1887. };
  1888. return retVal;
  1889. }
  1890. function responseWaitResolveFtn(responseFileState) {
  1891. // coderstate: resolver
  1892. let retVal = undefined;
  1893. do {
  1894. delete uxpContext.tqlRequestsByID[tqlRequest.requestID];
  1895. if (! responseFileState) {
  1896. consoleLog("evalTQL responseWaitResolveFtn timed out waiting for file");
  1897. break;
  1898. }
  1899. let replyByteArray;
  1900. function unlinkResolveFtn() {
  1901. // coderstate: resolver
  1902. return handleResponseData(replyByteArray);
  1903. };
  1904. function unlinkRejectFtn(reason) {
  1905. // coderstate: rejector
  1906. consoleLog("evalTQL responseWaitResolveFtn rejected for " + reason);
  1907. return handleResponseData(replyByteArray);
  1908. };
  1909. try {
  1910. replyByteArray = new Uint8Array(uxpContext.fs.readFileSync(responseFilePath));
  1911. retVal = uxpContext.fs.unlink(responseFilePath).then(
  1912. unlinkResolveFtn,
  1913. unlinkRejectFtn
  1914. );
  1915. }
  1916. catch (err) {
  1917. consoleLog("evalTQL responseWaitResolveFtn throws " + err);
  1918. }
  1919. }
  1920. while (false);
  1921. return retVal;
  1922. };
  1923. function responseWaitRejectFtn(reason) {
  1924. // coderstate: rejector
  1925. consoleLog("evalTQL responseWaitRejectFtn rejected for " + reason);
  1926. delete uxpContext.tqlRequestsByID[tqlRequest.requestID];
  1927. return undefined;
  1928. };
  1929. try {
  1930. uxpContext.fs.writeFileSync(requestFilePath, new Uint8Array(tqlRequestByteArray));
  1931. }
  1932. catch (err) {
  1933. consoleLog("evalTQL writeFileSync failed " + err);
  1934. break;
  1935. }
  1936. if (! wait) {
  1937. retVal = RESOLVED_PROMISE_UNDEFINED;
  1938. break;
  1939. }
  1940. retVal =
  1941. crdtuxp.waitForFile(
  1942. responseFilePath,
  1943. waitFileCheckInterval,
  1944. waitFileTimeout
  1945. ).then(
  1946. responseWaitResolveFtn,
  1947. responseWaitRejectFtn
  1948. );
  1949. break;
  1950. }
  1951. const init = {
  1952. method: "POST",
  1953. body: tqlScript
  1954. };
  1955. const responsePromise =
  1956. fetch(LOCALHOST_URL + "/" + tqlScopeName + "?" + HTTP_CACHE_BUSTER, init);
  1957. HTTP_CACHE_BUSTER = HTTP_CACHE_BUSTER + 1;
  1958. if (! wait) {
  1959. retVal = RESOLVED_PROMISE_UNDEFINED;
  1960. break;
  1961. }
  1962. if (! responsePromise) {
  1963. break;
  1964. }
  1965. function evalTQLResolveFtn(response) {
  1966. // coderstate: resolver
  1967. const responseTextPromise = response.text();
  1968. function responseTextResolveFtn(responseText) {
  1969. // coderstate: resolver
  1970. let retVal;
  1971. do {
  1972. let responseTextUnwrapped;
  1973. if (! responseText) {
  1974. break;
  1975. }
  1976. if (responseText == "undefined") {
  1977. break;
  1978. }
  1979. try {
  1980. if (resultIsRawBinary) {
  1981. responseTextUnwrapped = responseText;
  1982. }
  1983. else {
  1984. responseTextUnwrapped = binaryUTF8ToStr(deQuote(responseText));
  1985. }
  1986. }
  1987. catch (err) {
  1988. consoleLog("evalTQL responseTextResolveFtn throws " + err);
  1989. retVal = {
  1990. error: err
  1991. };
  1992. break;
  1993. }
  1994. retVal = {
  1995. text: responseTextUnwrapped
  1996. };
  1997. }
  1998. while (false);
  1999. return retVal;
  2000. };
  2001. function responseTextRejectFtn(reason) {
  2002. // coderstate: rejector
  2003. consoleLog("evalTQL responseTextRejectFtn rejected for " + reason);
  2004. return {
  2005. error: reason
  2006. };
  2007. };
  2008. return responseTextPromise.then(
  2009. responseTextResolveFtn,
  2010. responseTextRejectFtn
  2011. );
  2012. };
  2013. function evalTQLRejectFtn(reason) {
  2014. // coderstate: rejector
  2015. consoleLog("evalTQL evalTQLRejectFtn rejected for " + reason);
  2016. return {
  2017. error: reason
  2018. };
  2019. };
  2020. retVal = responsePromise.then(
  2021. evalTQLResolveFtn,
  2022. evalTQLRejectFtn
  2023. );
  2024. }
  2025. catch (err) {
  2026. consoleLog("evalTQL throws " + err);
  2027. }
  2028. }
  2029. while (false);
  2030. return retVal;
  2031. }
  2032. module.exports.evalTQL = evalTQL;
  2033. /**
  2034. * (Internal) Inefficient file append, for debugging use
  2035. *
  2036. * @function fileAppend_
  2037. *
  2038. * @param {string} filePath - file to append to
  2039. * @param {string} data - string to append
  2040. */
  2041. function fileAppend_(filePath, data) {
  2042. // coderstate: function
  2043. do {
  2044. // This is a low-level function. Do not call consoleLog or crdtuxp.logError.
  2045. let uxpContext = getUXPContext();
  2046. if (! uxpContext.hasDirectFileAccess) {
  2047. console.log("fileAppend_ needs hasDirectFileAccess");
  2048. break;
  2049. }
  2050. let fileExists;
  2051. try {
  2052. const stats = uxpContext.fs.lstatSync(filePath);
  2053. fileExists = stats && stats.isFile();
  2054. }
  2055. catch (err) {
  2056. if (err != FILE_NOT_EXIST_ERROR) {
  2057. console.log("fileAppend_ lstatSync throws " + err);
  2058. }
  2059. }
  2060. let oldData = "";
  2061. if (fileExists) {
  2062. try {
  2063. oldData = binaryUTF8ToStr(new Uint8Array(uxpContext.fs.readFileSync(filePath)));
  2064. }
  2065. catch (err) {
  2066. console.log("fileAppend_ readFileSync throws " + err);
  2067. }
  2068. }
  2069. try {
  2070. uxpContext.fs.writeFileSync(filePath, oldData + data);
  2071. }
  2072. catch (err) {
  2073. console.log("fileAppend_ writeFileSync throws " + err);
  2074. }
  2075. }
  2076. while (false);
  2077. }
  2078. module.exports.fileAppend_ = fileAppend_;
  2079. /**
  2080. * Append a string to a file (useful for logging).<br>
  2081. * <br>
  2082. * Not restricted by the UXP security sandbox.
  2083. *
  2084. * @function fileAppendString
  2085. * @memberof crdtuxp
  2086. *
  2087. * @param {string} fileName - path to file
  2088. * @param {string} appendStr - data to append. If a newline is needed it needs to be part of appendStr
  2089. * @param {object=} options - <code>{<br>
  2090. * options.wait = false means don't wait to resolve<br>
  2091. * }</code>
  2092. * @returns {Promise<boolean|undefined>} success or failure
  2093. */
  2094. function fileAppendString(fileName, in_appendStr, options) {
  2095. // coderstate: promisor
  2096. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2097. do {
  2098. try {
  2099. // Don't try direct file access - Photoshop UXPScript lacks an
  2100. // append function
  2101. let waitForLogConfirmation = true;
  2102. if (options && ! options.wait) {
  2103. waitForLogConfirmation = false;
  2104. }
  2105. let evalTQLOptions = {
  2106. wait: waitForLogConfirmation
  2107. };
  2108. const responsePromise = evalTQL(
  2109. "var retVal = true;" +
  2110. "var handle = fileOpen(" + dQ(fileName) + ",'a');" +
  2111. "if (! handle) {" +
  2112. "retVal = false;" +
  2113. "}" +
  2114. "else if (! fileWrite(handle, " + dQ(in_appendStr) + ")) {" +
  2115. "retVal = false;" +
  2116. "}" +
  2117. "if (! fileClose(handle)) {" +
  2118. "retVal = false;" +
  2119. "}" +
  2120. "retVal ? \"true\" : \"false\"",
  2121. evalTQLOptions
  2122. );
  2123. if (options && ! options.wait) {
  2124. retVal = RESOLVED_PROMISE_UNDEFINED;
  2125. break;
  2126. }
  2127. if (! responsePromise) {
  2128. break;
  2129. }
  2130. function evalTQLResolveFtn(response) {
  2131. // coderstate: resolver
  2132. let retVal;
  2133. do {
  2134. if (! response || response.error) {
  2135. consoleLog("fileAppendString bad response, error = " + response?.error);
  2136. break;
  2137. }
  2138. retVal = response.text == "true";
  2139. }
  2140. while (false);
  2141. return retVal;
  2142. };
  2143. function evalTQLRejectFtn(reason) {
  2144. // coderstate: rejector
  2145. consoleLog("fileAppendString rejected for " + reason);
  2146. return undefined;
  2147. };
  2148. retVal = responsePromise.then(
  2149. evalTQLResolveFtn,
  2150. evalTQLRejectFtn
  2151. );
  2152. }
  2153. catch (err) {
  2154. consoleLog("fileAppendString throws " + err);
  2155. }
  2156. }
  2157. while (false);
  2158. return retVal;
  2159. }
  2160. module.exports.fileAppendString = fileAppendString;
  2161. /**
  2162. * Close a currently open file.<br>
  2163. * <br>
  2164. * Not restricted by the UXP security sandbox.
  2165. *
  2166. * @function fileClose
  2167. * @memberof crdtuxp
  2168. *
  2169. * @param {number} fileHandle - a file handle as returned by <code>crdtuxp.fileOpen()</code>.
  2170. * @returns {Promise<boolean|undefined>} success or failure
  2171. */
  2172. function fileClose(fileHandle) {
  2173. // coderstate: promisor
  2174. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2175. do {
  2176. try {
  2177. let context = getContext();
  2178. let uxpContext = getUXPContext();
  2179. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  2180. let fileInfo = uxpContext.fileInfoByFileHandle[fileHandle];
  2181. if (! fileInfo) {
  2182. break;
  2183. }
  2184. delete uxpContext.fileInfoByFileHandle[fileHandle];
  2185. retVal = RESOLVED_PROMISE_TRUE;
  2186. break;
  2187. }
  2188. const responsePromise =
  2189. evalTQL(
  2190. "fileClose(" + fileHandle + ") ? \"true\" : \"false\""
  2191. );
  2192. if (! responsePromise) {
  2193. break;
  2194. }
  2195. function evalTQLResolveFtn(response) {
  2196. // coderstate: resolver
  2197. let retVal;
  2198. do {
  2199. if (! response || response.error) {
  2200. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2201. break;
  2202. }
  2203. retVal = response.text == "true";
  2204. }
  2205. while (false);
  2206. return retVal;
  2207. };
  2208. function evalTQLRejectFtn(reason) {
  2209. // coderstate: rejector
  2210. crdtuxp.logError(arguments, "rejected for " + reason);
  2211. return undefined;
  2212. };
  2213. retVal = responsePromise.then(
  2214. evalTQLResolveFtn,
  2215. evalTQLRejectFtn
  2216. );
  2217. }
  2218. catch (err) {
  2219. crdtuxp.logError(arguments, "throws " + err);
  2220. }
  2221. }
  2222. while (false);
  2223. return retVal;
  2224. }
  2225. module.exports.fileClose = fileClose;
  2226. /**
  2227. * Copy a file.<br>
  2228. * <br>
  2229. * Not restricted by the UXP security sandbox.
  2230. *
  2231. * @function fileCopy
  2232. * @memberof crdtuxp
  2233. *
  2234. * @param {string} fileFromPath - file to copy
  2235. * @param {string} fileToPath - where to copy to
  2236. * @returns {Promise<boolean|undefined>} success or failure
  2237. */
  2238. function fileCopy(fileFromPath, fileToPath) {
  2239. // coderstate: promisor
  2240. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2241. do {
  2242. try {
  2243. const responsePromise =
  2244. evalTQL(
  2245. "fileCopy(" + dQ(fileFromPath) + "," + dQ(fileToPath) + ") ? \"true\" : \"false\""
  2246. );
  2247. if (! responsePromise) {
  2248. break;
  2249. }
  2250. function evalTQLResolveFtn(response) {
  2251. // coderstate: resolver
  2252. let retVal;
  2253. do {
  2254. if (! response || response.error) {
  2255. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2256. break;
  2257. }
  2258. retVal = response.text == "true";
  2259. }
  2260. while (false);
  2261. return retVal;
  2262. };
  2263. function evalTQLRejectFtn(reason) {
  2264. // coderstate: rejector
  2265. crdtuxp.logError(arguments, "rejected for " + reason);
  2266. return undefined;
  2267. };
  2268. retVal = responsePromise.then(
  2269. evalTQLResolveFtn,
  2270. evalTQLRejectFtn
  2271. );
  2272. }
  2273. catch (err) {
  2274. crdtuxp.logError(arguments, "throws " + err);
  2275. }
  2276. }
  2277. while (false);
  2278. return retVal;
  2279. }
  2280. module.exports.fileCopy = fileCopy;
  2281. /**
  2282. * Delete a file.<br>
  2283. * <br>
  2284. * Not restricted by the UXP security sandbox.
  2285. *
  2286. * @function fileDelete
  2287. * @memberof crdtuxp
  2288. *
  2289. * @param {string} filePath
  2290. * @returns {Promise<boolean|undefined>} success or failure
  2291. */
  2292. function fileDelete(filePath) {
  2293. // coderstate: promisor
  2294. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2295. do {
  2296. try {
  2297. let context = getContext();
  2298. let uxpContext = getUXPContext();
  2299. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  2300. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  2301. try {
  2302. const stats = uxpContext.fs.lstatSync(filePath);
  2303. if (! stats || ! stats.isFile()) {
  2304. retVal = RESOLVED_PROMISE_FALSE;
  2305. break;
  2306. }
  2307. }
  2308. catch (err) {
  2309. if (err != FILE_NOT_EXIST_ERROR) {
  2310. crdtuxp.logNote(arguments, "throws " + err);
  2311. }
  2312. break;
  2313. }
  2314. try {
  2315. function unlinkResolveFtn() {
  2316. // coderstate: resolver
  2317. return true;
  2318. };
  2319. function unlinkRejectFtn(reason) {
  2320. // coderstate: rejector
  2321. crdtuxp.logError(arguments, "rejected for " + reason);
  2322. return false;
  2323. };
  2324. // If no callback given, returns a Promise
  2325. retVal = uxpContext.fs.unlink(filePath).then(
  2326. unlinkResolveFtn,
  2327. unlinkRejectFtn
  2328. );
  2329. }
  2330. catch (err) {
  2331. }
  2332. break;
  2333. }
  2334. const responsePromise =
  2335. evalTQL(
  2336. "fileDelete(" + dQ(filePath) + ") ? \"true\" : \"false\""
  2337. );
  2338. if (! responsePromise) {
  2339. break;
  2340. }
  2341. function evalTQLResolveFtn(response) {
  2342. // coderstate: resolver
  2343. let retVal;
  2344. do {
  2345. if (! response || response.error) {
  2346. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2347. break;
  2348. }
  2349. retVal = response.text == "true";
  2350. }
  2351. while (false);
  2352. return retVal;
  2353. };
  2354. function evalTQLRejectFtn(reason) {
  2355. // coderstate: rejector
  2356. crdtuxp.logError(arguments, "rejected for " + reason);
  2357. return undefined;
  2358. };
  2359. retVal = responsePromise.then(
  2360. evalTQLResolveFtn,
  2361. evalTQLRejectFtn
  2362. );
  2363. }
  2364. catch (err) {
  2365. crdtuxp.logError(arguments, "throws " + err);
  2366. }
  2367. }
  2368. while (false);
  2369. return retVal;
  2370. }
  2371. module.exports.fileDelete = fileDelete;
  2372. /**
  2373. * Check if a file exists. Will return <code>false</code> if the file path points to a directory.<br>
  2374. * <br>
  2375. * Also see <code>crdtuxp.dirExists()</code>.<br>
  2376. * <br>
  2377. * Not restricted by the UXP security sandbox.
  2378. *
  2379. * @function fileExists
  2380. * @memberof crdtuxp
  2381. *
  2382. * @param {string} filePath
  2383. * @returns {Promise<boolean|undefined>} existence of file
  2384. */
  2385. function fileExists(filePath) {
  2386. // coderstate: promisor
  2387. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2388. do {
  2389. try {
  2390. let context = getContext();
  2391. let uxpContext = getUXPContext();
  2392. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  2393. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  2394. try {
  2395. const stats = uxpContext.fs.lstatSync(filePath);
  2396. if (! stats || ! stats.isFile()) {
  2397. retVal = RESOLVED_PROMISE_FALSE;
  2398. break;
  2399. }
  2400. }
  2401. catch (err) {
  2402. if (err != FILE_NOT_EXIST_ERROR) {
  2403. crdtuxp.logNote(arguments, "throws " + err);
  2404. }
  2405. break;
  2406. }
  2407. retVal = Promise.resolve(true);
  2408. break;
  2409. }
  2410. const responsePromise =
  2411. evalTQL(
  2412. "fileExists(" + dQ(filePath) + ") ? \"true\" : \"false\""
  2413. );
  2414. if (! responsePromise) {
  2415. break;
  2416. }
  2417. function evalTQLResolveFtn(response) {
  2418. // coderstate: resolver
  2419. let retVal;
  2420. do {
  2421. if (! response || response.error) {
  2422. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2423. break;
  2424. }
  2425. retVal = response.text == "true";
  2426. }
  2427. while (false);
  2428. return retVal;
  2429. };
  2430. function evalTQLRejectFtn(reason) {
  2431. // coderstate: rejector
  2432. crdtuxp.logError(arguments, "rejected for " + reason);
  2433. return undefined;
  2434. };
  2435. retVal = responsePromise.then(
  2436. evalTQLResolveFtn,
  2437. evalTQLRejectFtn
  2438. );
  2439. }
  2440. catch (err) {
  2441. crdtuxp.logError(arguments, "throws " + err);
  2442. }
  2443. }
  2444. while (false);
  2445. return retVal;
  2446. }
  2447. module.exports.fileExists = fileExists;
  2448. /**
  2449. * Get the file name extension of a path
  2450. *
  2451. * @function fileNameExtension
  2452. * @memberof crdtuxp.path
  2453. *
  2454. * @param {string} filePath - a file path
  2455. * @param {string=} separator - the separator to use. If omitted, will try to guess the separator.
  2456. * @returns the lowercased file name extension, without leading period
  2457. */
  2458. function fileNameExtension(filePath, separator) {
  2459. // coderstate: function
  2460. let retVal;
  2461. try {
  2462. let splitName = crdtuxp.path.baseName(filePath).split(".");
  2463. let extension = "";
  2464. if (splitName.length > 1) {
  2465. extension = splitName.pop();
  2466. }
  2467. retVal = extension.toLowerCase();
  2468. }
  2469. catch (err) {
  2470. crdtuxp.logError(arguments, "throws " + err);
  2471. }
  2472. return retVal;
  2473. }
  2474. module.exports.path.fileNameExtension = fileNameExtension;
  2475. /**
  2476. * Open a binary file and return a handle.<br>
  2477. * <br>
  2478. * Not restricted by the UXP security sandbox.
  2479. *
  2480. * @function fileOpen
  2481. * @memberof crdtuxp
  2482. *
  2483. * @param {string} filePath - a native full file path to the file
  2484. * @param {string} mode - one of <code>'a'</code>, <code>'r'</code>, <code>'w'</code> (append, read, write)
  2485. * @returns {Promise<Number|undefined>} file handle
  2486. */
  2487. function fileOpen(filePath, mode) {
  2488. // coderstate: promisor
  2489. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2490. do {
  2491. try {
  2492. let context = getContext();
  2493. let uxpContext = getUXPContext();
  2494. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  2495. let parentPath = crdtuxp.path.dirName(filePath);
  2496. let baseName = crdtuxp.path.baseName(filePath);
  2497. if (! uxpContext.uniqueFileHandleID) {
  2498. uxpContext.uniqueFileHandleID = 0;
  2499. uxpContext.fileInfoByFileHandle = {};
  2500. }
  2501. if (mode == 'w' || mode == 'a') {
  2502. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  2503. try {
  2504. const stats = uxpContext.fs.lstatSync(parentPath);
  2505. if (! stats || ! stats.isDirectory()) {
  2506. break;
  2507. }
  2508. }
  2509. catch (err) {
  2510. if (err != FILE_NOT_EXIST_ERROR) {
  2511. crdtuxp.logNote(arguments, "throws " + err);
  2512. }
  2513. break;
  2514. }
  2515. let uniqueFileHandleID = ++uxpContext.uniqueFileHandleID;
  2516. let fileInfo = {
  2517. fileHandle: uniqueFileHandleID,
  2518. filePath: filePath,
  2519. mode: mode
  2520. }
  2521. uxpContext.fileInfoByFileHandle[uniqueFileHandleID] = fileInfo;
  2522. retVal = Promise.resolve(uniqueFileHandleID);
  2523. }
  2524. else if (mode == 'r') {
  2525. try {
  2526. const stats = uxpContext.fs.lstatSync(filePath);
  2527. if (! stats || ! stats.isFile()) {
  2528. break;
  2529. }
  2530. }
  2531. catch (err) {
  2532. if (err != FILE_NOT_EXIST_ERROR) {
  2533. crdtuxp.logNote(arguments, "throws " + err);
  2534. }
  2535. break;
  2536. }
  2537. let uniqueFileHandleID = ++uxpContext.uniqueFileHandleID;
  2538. let fileInfo = {
  2539. fileHandle: uniqueFileHandleID,
  2540. filePath: filePath,
  2541. mode: mode
  2542. }
  2543. uxpContext.fileInfoByFileHandle[uniqueFileHandleID] = fileInfo;
  2544. retVal = Promise.resolve(uniqueFileHandleID);
  2545. }
  2546. break;
  2547. }
  2548. let responsePromise;
  2549. if (mode) {
  2550. responsePromise =
  2551. evalTQL(
  2552. "enquote(fileOpen(" + dQ(filePath) + "," + dQ(mode) + "))"
  2553. );
  2554. }
  2555. else {
  2556. responsePromise =
  2557. evalTQL(
  2558. "enquote(fileOpen(" + dQ(filePath) + "))"
  2559. );
  2560. }
  2561. if (! responsePromise) {
  2562. break;
  2563. }
  2564. function evalTQLResolveFtn(response) {
  2565. // coderstate: resolver
  2566. let retVal;
  2567. do {
  2568. try {
  2569. if (! response || response.error) {
  2570. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2571. break;
  2572. }
  2573. let responseStr = deQuote(response.text);
  2574. if (! responseStr) {
  2575. crdtuxp.logError(arguments, "no responseStr");
  2576. break;
  2577. }
  2578. let responseData = binaryUTF8ToStr(responseStr);
  2579. if (! responseData) {
  2580. crdtuxp.logError(arguments, "no responseData");
  2581. break;
  2582. }
  2583. retVal = parseInt(responseData, 10);
  2584. if (isNaN(retVal)) {
  2585. crdtuxp.logError(arguments, "not a number " + responseData);
  2586. retVal = undefined;
  2587. break;
  2588. }
  2589. }
  2590. catch (err) {
  2591. crdtuxp.logError(arguments, "throws " + err);
  2592. break;
  2593. }
  2594. }
  2595. while (false);
  2596. return retVal;
  2597. };
  2598. function evalTQLRejectFtn(reason) {
  2599. // coderstate: rejector
  2600. crdtuxp.logError(arguments, "rejected for " + reason);
  2601. return undefined;
  2602. };
  2603. retVal = responsePromise.then(
  2604. evalTQLResolveFtn,
  2605. evalTQLRejectFtn
  2606. );
  2607. }
  2608. catch (err) {
  2609. crdtuxp.logError(arguments, "throws " + err);
  2610. }
  2611. }
  2612. while (false);
  2613. return retVal;
  2614. }
  2615. module.exports.fileOpen = fileOpen;
  2616. /**
  2617. * Read a file into memory.<br>
  2618. * <br>
  2619. * Not restricted by the UXP security sandbox.
  2620. *
  2621. * @function fileRead
  2622. * @memberof crdtuxp
  2623. *
  2624. * @param {number} fileHandle - a file handle as returned by <code>crdtuxp.fileOpen()</code>.
  2625. * @param {boolean|object=} options - <code>{ isBinary: true/false, default false }</code>
  2626. * @returns {Promise<any>} either a byte array or a string
  2627. */
  2628. function fileRead(fileHandle, options) {
  2629. // coderstate: promisor
  2630. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2631. do {
  2632. try {
  2633. if ("boolean" == typeof options) {
  2634. options = {
  2635. isBinary: options
  2636. };
  2637. }
  2638. let context = getContext();
  2639. let uxpContext = getUXPContext();
  2640. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  2641. if (! uxpContext.fileInfoByFileHandle) {
  2642. break;
  2643. }
  2644. let fileInfo = uxpContext.fileInfoByFileHandle[fileHandle];
  2645. if (! fileInfo) {
  2646. break;
  2647. }
  2648. if (fileInfo.mode != 'r') {
  2649. break;
  2650. }
  2651. let replyByteArray;
  2652. try {
  2653. replyByteArray = new Uint8Array(uxpContext.fs.readFileSync(fileInfo.filePath));
  2654. if (options?.isBinary) {
  2655. retVal = Promise.resolve(replyByteArray);
  2656. break;
  2657. }
  2658. }
  2659. catch (err) {
  2660. crdtuxp.logError(arguments, "throws " + err);
  2661. break;
  2662. }
  2663. retVal = Promise.resolve(binaryUTF8ToStr(replyByteArray));
  2664. break;
  2665. }
  2666. let evalTQLOptions = {
  2667. isBinary: options?.isBinary
  2668. };
  2669. const responsePromise =
  2670. evalTQL(
  2671. "enquote(fileRead(" + fileHandle + "))",
  2672. evalTQLOptions);
  2673. if (! responsePromise) {
  2674. break;
  2675. }
  2676. function evalTQLResolveFtn(response) {
  2677. // coderstate: resolver
  2678. let retVal;
  2679. do {
  2680. if (! response || response.error) {
  2681. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2682. break;
  2683. }
  2684. let byteArrayStr = deQuote(response.text);
  2685. if (! byteArrayStr) {
  2686. crdtuxp.logError(arguments, "no byteArrayStr");
  2687. break;
  2688. }
  2689. var str = binaryUTF8ToStr(byteArrayStr);
  2690. if (! str) {
  2691. crdtuxp.logError(arguments, "no str");
  2692. break;
  2693. }
  2694. if (! options?.isBinary) {
  2695. retVal = str;
  2696. break;
  2697. }
  2698. retVal = deQuote(str);
  2699. }
  2700. while (false);
  2701. return retVal;
  2702. };
  2703. function evalTQLRejectFtn(reason) {
  2704. // coderstate: rejector
  2705. crdtuxp.logError(arguments, "rejected for " + reason);
  2706. return undefined;
  2707. };
  2708. retVal = responsePromise.then(
  2709. evalTQLResolveFtn,
  2710. evalTQLRejectFtn
  2711. );
  2712. }
  2713. catch (err) {
  2714. crdtuxp.logError(arguments, "throws " + err);
  2715. }
  2716. }
  2717. while (false);
  2718. return retVal;
  2719. }
  2720. module.exports.fileRead = fileRead;
  2721. /**
  2722. * Binary write to a file. Strings are written as UTF-8.<br>
  2723. * <br>
  2724. * Not restricted by the UXP security sandbox.
  2725. *
  2726. * @function fileWrite
  2727. * @memberof crdtuxp
  2728. *
  2729. * @param {number} fileHandle - a file handle as returned by <code>crdtuxp.fileOpen()</code>.
  2730. * @param {string|Array} s_or_ByteArr - data to write to the file
  2731. * @returns {Promise<boolean|undefined>} success or failure
  2732. */
  2733. function fileWrite(fileHandle, s_or_ByteArr) {
  2734. // coderstate: promisor
  2735. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2736. do {
  2737. try {
  2738. let byteArray;
  2739. if ("string" == typeof s_or_ByteArr) {
  2740. byteArray = strToUTF8(s_or_ByteArr);
  2741. }
  2742. else {
  2743. byteArray = s_or_ByteArr;
  2744. }
  2745. let context = getContext();
  2746. let uxpContext = getUXPContext();
  2747. if (uxpContext.hasDirectFileAccess && ! context.IS_FORCE_USE_DAEMON) {
  2748. if (! uxpContext.fileInfoByFileHandle) {
  2749. break;
  2750. }
  2751. let fileInfo = uxpContext.fileInfoByFileHandle[fileHandle];
  2752. if (! fileInfo) {
  2753. break;
  2754. }
  2755. if (fileInfo.mode != 'w' && fileInfo.mode != 'a') {
  2756. break;
  2757. }
  2758. let lengthWritten = 0;
  2759. try {
  2760. lengthWritten = uxpContext.fs.writeFileSync(fileInfo.filePath, new Uint8Array(byteArray));
  2761. }
  2762. catch (err) {
  2763. crdtuxp.logError(arguments, "throws " + err);
  2764. break;
  2765. }
  2766. retVal = Promise.resolve(lengthWritten == byteArray.length);
  2767. break;
  2768. }
  2769. const responsePromise =
  2770. evalTQL(
  2771. "fileWrite(" + fileHandle + "," + dQ(byteArray) + ") ? \"true\" : \"false\""
  2772. );
  2773. if (! responsePromise) {
  2774. break;
  2775. }
  2776. function evalTQLResolveFtn(response) {
  2777. // coderstate: resolver
  2778. let retVal;
  2779. do {
  2780. if (! response || response.error) {
  2781. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2782. break;
  2783. }
  2784. retVal = response.text == "true";
  2785. }
  2786. while (false);
  2787. return retVal;
  2788. };
  2789. function evalTQLRejectFtn(reason) {
  2790. // coderstate: rejector
  2791. crdtuxp.logError(arguments, "rejected for " + reason);
  2792. return undefined;
  2793. };
  2794. retVal = responsePromise.then(
  2795. evalTQLResolveFtn,
  2796. evalTQLRejectFtn
  2797. );
  2798. }
  2799. catch (err) {
  2800. crdtuxp.logError(arguments, "throws " + err);
  2801. }
  2802. }
  2803. while (false);
  2804. return retVal;
  2805. }
  2806. module.exports.fileWrite = fileWrite;
  2807. /**
  2808. * Terminate crdtuxp
  2809. *
  2810. * @function finalize
  2811. * @memberof crdtuxp
  2812. */
  2813. function finalize() {
  2814. // coderstate: promisor
  2815. return Promise.finalizePromises();
  2816. }
  2817. module.exports.finalize = finalize;
  2818. /**
  2819. * Extract the function name from its arguments
  2820. *
  2821. * @function functionNameFromArguments
  2822. * @memberof crdtuxp
  2823. *
  2824. * @param {object} functionArguments - pass in the current <code>arguments</code> to the function. This is used to determine the function's name
  2825. * @returns {string} function name
  2826. */
  2827. function functionNameFromArguments(functionArguments) {
  2828. // coderstate: function
  2829. let functionName;
  2830. try {
  2831. functionName = functionArguments.callee.toString().match(/function ([^\(]+)/)[1];
  2832. }
  2833. catch (err) {
  2834. functionName = "[anonymous function]";
  2835. }
  2836. return functionName;
  2837. }
  2838. module.exports.functionNameFromArguments = functionNameFromArguments;
  2839. /**
  2840. * Interpret a value extracted from some INI data as a boolean. Things like <code>y, n, yes, no, true, false, t, f, 0, 1</code><br>
  2841. * Default if missing is <code>false</code>
  2842. *
  2843. * @function getBooleanFromINI
  2844. * @memberof crdtuxp
  2845. *
  2846. * @param {string} in_value - ini value
  2847. * @param {string} in_default - value to use if <code>undefined</code> or <code>""</code>
  2848. * @returns {boolean} value
  2849. */
  2850. function getBooleanFromINI(in_value, in_default) {
  2851. // coderstate: function
  2852. let retVal = false;
  2853. try {
  2854. if (! in_value) {
  2855. retVal = in_default ? true : false;
  2856. }
  2857. else {
  2858. const value = (in_value + "").replace(REGEXP_TRIM, REGEXP_TRIM_REPLACE);
  2859. if (! value) {
  2860. retVal = in_default ? true : false;
  2861. }
  2862. else {
  2863. const firstChar = value.charAt(0).toLowerCase();
  2864. const firstValue = parseInt(firstChar, 10);
  2865. retVal = firstChar == "y" || firstChar == "t" || (! isNaN(firstValue) && firstValue != 0);
  2866. }
  2867. }
  2868. }
  2869. catch (err) {
  2870. crdtuxp.logError(arguments, "throws " + err);
  2871. }
  2872. return retVal;
  2873. }
  2874. module.exports.getBooleanFromINI = getBooleanFromINI;
  2875. /**
  2876. * Query the daemon to see whether some software is currently activated or not
  2877. *
  2878. * @function getCapability
  2879. * @memberof crdtuxp
  2880. *
  2881. * @param {string} issuer - a GUID identifier for the developer account as seen in the PluginInstaller
  2882. * @param {string} capabilityCode - a code for the software features to be activated (as determined by<br>
  2883. * the developer who owns the account).<br>
  2884. * <code>capabilityCode</code> is not the same as <code>orderProductCode</code> - there can be multiple<br>
  2885. * <code>orderProductCode</code> associated with a single <code>capabilityCode</code><br>
  2886. * (e.g. <code>capabilityCode</code> 'XYZ', <code>orderProductCode</code> 'XYZ_1YEAR', 'XYZ_2YEAR'...).
  2887. * @param {string} encryptionKey - the secret encryption key (created by the developer) needed to decode<br>
  2888. * the capability data. You want to make sure this password is obfuscated and contained within encrypted script code.
  2889. * @returns {Promise<string|undefined>} a JSON-encoded object with meta object (containing customer GUID, seatIndex,<br>
  2890. * decrypted developer-provided data from the activation file).<br>
  2891. * The decrypted developer data is embedded as a string, so might be two levels of JSON-encoding to be dealt with <br>
  2892. * to get to any JSON-encoded decrypted data
  2893. */
  2894. function getCapability(issuer, capabilityCode, encryptionKey) {
  2895. // coderstate: promisor
  2896. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2897. do {
  2898. try {
  2899. const responsePromise =
  2900. evalTQL(
  2901. "getCapability(" +
  2902. dQ(issuer) + ", " +
  2903. dQ(capabilityCode) + ", " +
  2904. dQ(encryptionKey) +
  2905. ")"
  2906. );
  2907. if (! responsePromise) {
  2908. break;
  2909. }
  2910. function evalTQLResolveFtn(response) {
  2911. // coderstate: resolver
  2912. let retVal;
  2913. do {
  2914. if (response && response.error) {
  2915. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2916. break;
  2917. }
  2918. if (! response) {
  2919. break;
  2920. }
  2921. retVal = response.text;
  2922. }
  2923. while (false);
  2924. return retVal;
  2925. };
  2926. function evalTQLRejectFtn(reason) {
  2927. // coderstate: rejector
  2928. crdtuxp.logError(arguments, "rejected for " + reason);
  2929. return undefined;
  2930. };
  2931. retVal = responsePromise.then(
  2932. evalTQLResolveFtn,
  2933. evalTQLRejectFtn
  2934. );
  2935. }
  2936. catch (err) {
  2937. crdtuxp.logError(arguments, "throws " + err);
  2938. }
  2939. }
  2940. while (false);
  2941. return retVal;
  2942. }
  2943. module.exports.getCapability = getCapability;
  2944. /**
  2945. * Determine the license level for CRDT: 0 = not, 1 = basic, 2 = full<br>
  2946. * <br>
  2947. * Some functions, marked with "Only available to paid developer accounts" <br>
  2948. * will only work with level 2. Licensing function only work with level 1<br>
  2949. *
  2950. * @function getCreativeDeveloperToolsLevel
  2951. * @memberof crdtuxp
  2952. *
  2953. * @returns {Promise<Number|undefined>} - 0, 1 or 2. -1 means: error
  2954. */
  2955. function getCreativeDeveloperToolsLevel() {
  2956. // coderstate: promisor
  2957. let retVal = RESOLVED_PROMISE_UNDEFINED;
  2958. do {
  2959. try {
  2960. const responsePromise =
  2961. evalTQL(
  2962. "getCreativeDeveloperToolsLevel()"
  2963. );
  2964. if (! responsePromise) {
  2965. break;
  2966. }
  2967. function evalTQLResolveFtn(response) {
  2968. // coderstate: resolver
  2969. let retVal;
  2970. do {
  2971. if (! response || response.error) {
  2972. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  2973. break;
  2974. }
  2975. retVal = parseInt(response.text, 10);
  2976. if (isNaN(retVal)) {
  2977. crdtuxp.logError(arguments, "not a number " + response.text);
  2978. retVal = undefined;
  2979. break;
  2980. }
  2981. }
  2982. while (false);
  2983. return retVal;
  2984. };
  2985. function evalTQLRejectFtn(reason) {
  2986. // coderstate: rejector
  2987. crdtuxp.logError(arguments, "rejected for " + reason);
  2988. return undefined;
  2989. };
  2990. retVal = responsePromise.then(
  2991. evalTQLResolveFtn,
  2992. evalTQLRejectFtn
  2993. );
  2994. }
  2995. catch (err) {
  2996. crdtuxp.logError(arguments, "throws " + err);
  2997. }
  2998. }
  2999. while (false);
  3000. return retVal;
  3001. }
  3002. module.exports.getCreativeDeveloperToolsLevel = getCreativeDeveloperToolsLevel;
  3003. /**
  3004. * Get the path of the current script of the caller (<i>not</i> the path of this file).<br>
  3005. * <br>
  3006. * Not restricted by the UXP security sandbox.
  3007. *
  3008. * @function getCurrentScriptPath
  3009. * @memberof crdtuxp
  3010. *
  3011. * @returns {string|undefined} file path of the script file containing the caller of <code>crdtuxp.getCurrentScriptPath()</code>
  3012. */
  3013. function getCurrentScriptPath() {
  3014. let retVal = undefined;
  3015. try {
  3016. // Intentionally throw an error to capture the stack trace
  3017. throw new Error();
  3018. } catch (err) {
  3019. // Parse the stack trace to extract the script path
  3020. const stackLines = err.stack.split("\n");
  3021. // We are interested in the script path for the caller of this function, not the path for crdtuxp.js::getCurrentScriptPath
  3022. const NUM_STEPS_FROM_STACK_TOP = 2;
  3023. const scriptPathLine = stackLines[NUM_STEPS_FROM_STACK_TOP];
  3024. const scriptPathMatch = scriptPathLine.match(/(\/.*?|[A-Za-z]:\\.*?|\\\\.*?\\.*?):\d+:\d+/);
  3025. if (scriptPathMatch) {
  3026. retVal = scriptPathMatch[1];
  3027. }
  3028. }
  3029. return retVal;
  3030. }
  3031. module.exports.getCurrentScriptPath = getCurrentScriptPath;
  3032. /**
  3033. * Get the path of a system directory.<br>
  3034. * <br>
  3035. * Not restricted by the UXP security sandbox.
  3036. *
  3037. * @function getDir
  3038. * @memberof crdtuxp
  3039. *
  3040. * @param {string} dirTag - a tag representing the dir:
  3041. * <code><br>
  3042. * crdtuxp.DESKTOP_DIR<br>
  3043. * crdtuxp.DOCUMENTS_DIR<br>
  3044. * crdtuxp.HOME_DIR<br>
  3045. * crdtuxp.LOG_DIR<br>
  3046. * crdtuxp.SYSTEMDATA_DIR<br>
  3047. * crdtuxp.TMP_DIR<br>
  3048. * crdtuxp.USERDATA_DIR<br>
  3049. * </code>
  3050. * @returns {Promise<string|undefined>} file path of dir or undefined. Directory paths include a trailing slash or backslash.
  3051. */
  3052. function getDir(dirTag) {
  3053. // coderstate: promisor
  3054. let retVal = RESOLVED_PROMISE_UNDEFINED;
  3055. do {
  3056. try {
  3057. if (crdtuxp.context) {
  3058. if (dirTag == module.exports.DESKTOP_DIR && crdtuxp.context.PATH_DESKTOP) {
  3059. retVal = Promise.resolve(crdtuxp.context.PATH_DESKTOP);
  3060. break;
  3061. }
  3062. if (dirTag == module.exports.DOCUMENTS_DIR && crdtuxp.context.PATH_DOCUMENTS) {
  3063. retVal = Promise.resolve(crdtuxp.context.PATH_DOCUMENTS);
  3064. break;
  3065. }
  3066. if (dirTag == module.exports.HOME_DIR && crdtuxp.context.PATH_HOME) {
  3067. retVal = Promise.resolve(crdtuxp.context.PATH_HOME);
  3068. break;
  3069. }
  3070. if (dirTag == module.exports.LOG_DIR && crdtuxp.context.PATH_LOG) {
  3071. retVal = Promise.resolve(crdtuxp.context.PATH_LOG);
  3072. break;
  3073. }
  3074. if (dirTag == module.exports.SYSTEMDATA_DIR && crdtuxp.context.PATH_SYSTEMDATA) {
  3075. retVal = Promise.resolve(crdtuxp.context.PATH_SYSTEMDATA);
  3076. break;
  3077. }
  3078. if (dirTag == module.exports.TMP_DIR && crdtuxp.context.PATH_TMP) {
  3079. retVal = Promise.resolve(crdtuxp.context.PATH_TMP);
  3080. break;
  3081. }
  3082. if (dirTag == module.exports.USERDATA_DIR && crdtuxp.context.PATH_USERDATA) {
  3083. retVal = Promise.resolve(crdtuxp.context.PATH_USERDATA);
  3084. break;
  3085. }
  3086. }
  3087. const sysInfoPromise = getSysInfo__();
  3088. if (! sysInfoPromise) {
  3089. crdtuxp.logError(arguments, "no sysInfoPromise");
  3090. break;
  3091. }
  3092. function evalTQLResolveFtn(sysInfo) {
  3093. // coderstate: resolver
  3094. let retVal;
  3095. do {
  3096. if (! sysInfo || sysInfo.error) {
  3097. crdtuxp.logError(arguments, "bad response, error = " + sysInfo?.error);
  3098. break;
  3099. }
  3100. if (! (dirTag in sysInfo)) {
  3101. crdtuxp.logError(arguments, "unknown tag " + dirTag);
  3102. break;
  3103. }
  3104. retVal = sysInfo[dirTag];
  3105. }
  3106. while (false);
  3107. return retVal;
  3108. };
  3109. function evalTQLRejectFtn(reason) {
  3110. // coderstate: rejector
  3111. crdtuxp.logError(arguments, "rejected for " + reason);
  3112. return undefined;
  3113. };
  3114. retVal = sysInfoPromise.then(
  3115. evalTQLResolveFtn,
  3116. evalTQLRejectFtn
  3117. );
  3118. }
  3119. catch (err) {
  3120. crdtuxp.logError(arguments, "throws " + err);
  3121. }
  3122. }
  3123. while (false);
  3124. return retVal;
  3125. }
  3126. module.exports.getDir = getDir;
  3127. /**
  3128. * Access the environment as available to the daemon program.<br>
  3129. * <br>
  3130. * Not restricted by the UXP security sandbox.
  3131. *
  3132. * @function getEnvironment
  3133. * @memberof crdtuxp
  3134. *
  3135. * @param {string} envVarName - name of environment variable
  3136. * @returns {Promise<string>} environment variable value
  3137. */
  3138. function getEnvironment(envVarName) {
  3139. // coderstate: promisor
  3140. let retVal = RESOLVED_PROMISE_UNDEFINED;
  3141. do {
  3142. try {
  3143. const responsePromise =
  3144. evalTQL(
  3145. "getEnv(" + dQ(envVarName) + ")"
  3146. );
  3147. if (! responsePromise) {
  3148. break;
  3149. }
  3150. function evalTQLResolveFtn(response) {
  3151. // coderstate: resolver
  3152. let retVal;
  3153. do {
  3154. if (! response || response.error) {
  3155. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  3156. break;
  3157. }
  3158. retVal = response.text;
  3159. }
  3160. while (false);
  3161. return retVal;
  3162. };
  3163. function evalTQLRejectFtn(reason) {
  3164. // coderstate: rejector
  3165. crdtuxp.logError(arguments, "rejected for " + reason);
  3166. return undefined;
  3167. };
  3168. retVal = responsePromise.then(
  3169. evalTQLResolveFtn,
  3170. evalTQLRejectFtn
  3171. );
  3172. }
  3173. catch (err) {
  3174. crdtuxp.logError(arguments, "throws " + err);
  3175. }
  3176. }
  3177. while (false);
  3178. return retVal;
  3179. }
  3180. module.exports.getEnvironment = getEnvironment;
  3181. /**
  3182. * Interpret a string extracted from some INI data as a floating point value, followed by an optional unit<br>
  3183. * If there is no unit, then no conversion is performed.
  3184. *
  3185. * @function getFloatWithUnitFromINI
  3186. * @memberof crdtuxp
  3187. *
  3188. * @param {string} in_valueStr - ini value
  3189. * @param {string=} in_convertToUnit - default to use if no match is found
  3190. * @returns {number} value
  3191. */
  3192. function getFloatWithUnitFromINI(in_valueStr, in_convertToUnit) {
  3193. // coderstate: function
  3194. let retVal = 0.0;
  3195. do {
  3196. try {
  3197. if (! in_valueStr) {
  3198. break;
  3199. }
  3200. let convertToUnit;
  3201. if (in_convertToUnit) {
  3202. convertToUnit = in_convertToUnit;
  3203. }
  3204. else {
  3205. convertToUnit = crdtuxp.UNIT_NAME_NONE;
  3206. }
  3207. let sign = 1.0;
  3208. let valueStr = in_valueStr.replace(REGEXP_DESPACE, REGEXP_DESPACE_REPLACE).toLowerCase();
  3209. const firstChar = valueStr.charAt(0);
  3210. if (firstChar == '-') {
  3211. valueStr = valueStr.substring(1);
  3212. sign = -1.0;
  3213. }
  3214. else if (firstChar == '+') {
  3215. valueStr = valueStr.substring(1);
  3216. }
  3217. let picas = undefined;
  3218. let ciceros = undefined;
  3219. if (valueStr.match(REGEXP_PICAS)) {
  3220. picas = parseInt(valueStr.replace(REGEXP_PICAS, REGEXP_PICAS_REPLACE), 10);
  3221. valueStr = valueStr.replace(REGEXP_PICAS, REGEXP_PICAS_POINTS_REPLACE);
  3222. }
  3223. else if (valueStr.match(REGEXP_CICEROS)) {
  3224. ciceros = parseInt(valueStr.replace(REGEXP_CICEROS, REGEXP_CICEROS_REPLACE), 10);
  3225. valueStr = valueStr.replace(REGEXP_CICEROS, REGEXP_CICEROS_POINTS_REPLACE);
  3226. }
  3227. const numberOnlyStr = valueStr.replace(REGEXP_NUMBER_ONLY, REGEXP_NUMBER_ONLY_REPLACE);
  3228. let numberOnly = parseFloat(numberOnlyStr);
  3229. if (isNaN(numberOnly)) {
  3230. numberOnly = 0.0;
  3231. }
  3232. let fromUnit;
  3233. if (picas !== undefined) {
  3234. fromUnit = crdtuxp.UNIT_NAME_PICA;
  3235. numberOnly = picas + numberOnly / 6.0;
  3236. }
  3237. else if (ciceros !== undefined) {
  3238. fromUnit = crdtuxp.UNIT_NAME_CICERO;
  3239. numberOnly = ciceros + numberOnly / 6.0;
  3240. }
  3241. else {
  3242. let unitOnly = valueStr.replace(REGEXP_UNIT_ONLY, REGEXP_UNIT_ONLY_REPLACE);
  3243. fromUnit = getUnitFromINI(unitOnly, crdtuxp.UNIT_NAME_NONE);
  3244. }
  3245. let conversion = 1.0;
  3246. if (fromUnit != crdtuxp.UNIT_NAME_NONE && convertToUnit != crdtuxp.UNIT_NAME_NONE) {
  3247. conversion = unitToInchFactor(fromUnit) / unitToInchFactor(convertToUnit);
  3248. }
  3249. retVal = sign * numberOnly * conversion;
  3250. }
  3251. catch (err) {
  3252. crdtuxp.logError(arguments, "throws " + err);
  3253. }
  3254. }
  3255. while (false);
  3256. return retVal;
  3257. }
  3258. module.exports.getFloatWithUnitFromINI = getFloatWithUnitFromINI;
  3259. /**
  3260. * Interpret a string extracted from some INI data as an array with float values (e.g. <code>"[ 255, 128.2, 1.7]"</code> )
  3261. *
  3262. * @function getFloatValuesFromINI
  3263. * @memberof crdtuxp
  3264. *
  3265. * @param {string} in_valueStr - ini value
  3266. * @returns {array|undefined} array of numbers or undefined
  3267. */
  3268. function getFloatValuesFromINI(in_valueStr) {
  3269. // coderstate: function
  3270. let retVal = undefined;
  3271. do {
  3272. try {
  3273. if (! in_valueStr) {
  3274. break;
  3275. }
  3276. let floatValues = undefined;
  3277. const values = in_valueStr.split(",");
  3278. for (let idx = 0; idx < values.length; idx++) {
  3279. const value = values[idx].replace(REGEXP_TRIM, REGEXP_TRIM_REPLACE);
  3280. let numValue = 0;
  3281. if (value) {
  3282. numValue = parseFloat(value);
  3283. if (isNaN(numValue)) {
  3284. floatValues = undefined;
  3285. break;
  3286. }
  3287. }
  3288. if (! floatValues) {
  3289. floatValues = [];
  3290. }
  3291. floatValues.push(numValue);
  3292. }
  3293. retVal = floatValues;
  3294. }
  3295. catch (err) {
  3296. crdtuxp.logError(arguments, "throws " + err);
  3297. }
  3298. }
  3299. while (false);
  3300. return retVal;
  3301. }
  3302. module.exports.getFloatValuesFromINI = getFloatValuesFromINI;
  3303. /**
  3304. * Interpret a string extracted from some INI data as an array with int values (e.g. <code>"[ 255, 128, 1]"</code> )
  3305. *
  3306. * @function getIntValuesFromINI
  3307. * @memberof crdtuxp
  3308. *
  3309. * @param {string} in_valueStr - ini value
  3310. * @returns {array|undefined} array of ints or undefined
  3311. */
  3312. function getIntValuesFromINI(in_valueStr) {
  3313. // coderstate: function
  3314. let retVal = undefined;
  3315. do {
  3316. try {
  3317. if (! in_valueStr) {
  3318. break;
  3319. }
  3320. let intValues = undefined;
  3321. const values = in_valueStr.split(",");
  3322. for (let idx = 0; idx < values.length; idx++) {
  3323. const valueStr = values[idx].replace(REGEXP_TRIM, REGEXP_TRIM_REPLACE);
  3324. let value = 0;
  3325. if (! valueStr) {
  3326. value = 0;
  3327. }
  3328. else {
  3329. value = parseInt(valueStr, 10);
  3330. if (isNaN(value)) {
  3331. intValues = undefined;
  3332. break;
  3333. }
  3334. }
  3335. if (! intValues) {
  3336. intValues = [];
  3337. }
  3338. intValues.push(value);
  3339. }
  3340. retVal = intValues;
  3341. }
  3342. catch (err) {
  3343. crdtuxp.logError(arguments, "throws " + err);
  3344. }
  3345. }
  3346. while (false);
  3347. return retVal;
  3348. }
  3349. module.exports.getIntValuesFromINI = getIntValuesFromINI;
  3350. /**
  3351. * Query the daemon for persisted data<br>
  3352. * <br>
  3353. * Only available to paid developer accounts<br>
  3354. *
  3355. * @function getPersistData
  3356. * @memberof crdtuxp
  3357. *
  3358. * @param {string} issuer - a GUID identifier for the developer account as seen in the PluginInstaller
  3359. * @param {string} attribute - an attribute name for the data
  3360. * @param {string} password - the password (created by the developer) needed to decode the persistent data
  3361. * @returns {Promise<any>} whatever persistent data is stored for the given attribute
  3362. */
  3363. function getPersistData(issuer, attribute, password) {
  3364. // coderstate: promisor
  3365. let retVal = RESOLVED_PROMISE_UNDEFINED;
  3366. do {
  3367. try {
  3368. const responsePromise =
  3369. evalTQL(
  3370. "getPersistData(" +
  3371. dQ(issuer) + "," +
  3372. dQ(attribute) + "," +
  3373. dQ(password) +
  3374. ")"
  3375. );
  3376. if (! responsePromise) {
  3377. break;
  3378. }
  3379. function evalTQLResolveFtn(response) {
  3380. // coderstate: resolver
  3381. let retVal;
  3382. do {
  3383. if (! response || response.error) {
  3384. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  3385. break;
  3386. }
  3387. retVal = response.text;
  3388. }
  3389. while (false);
  3390. return retVal;
  3391. };
  3392. function evalTQLRejectFtn(reason) {
  3393. // coderstate: rejector
  3394. crdtuxp.logError(arguments, "rejected for " + reason);
  3395. return undefined;
  3396. };
  3397. retVal = responsePromise.then(
  3398. evalTQLResolveFtn,
  3399. evalTQLRejectFtn
  3400. );
  3401. }
  3402. catch (err) {
  3403. crdtuxp.logError(arguments, "throws " + err);
  3404. }
  3405. }
  3406. while (false);
  3407. return retVal;
  3408. }
  3409. module.exports.getPersistData = getPersistData;
  3410. /**
  3411. * Get file path to PluginInstaller if it is installed
  3412. *
  3413. * @function getPluginInstallerPath
  3414. * @memberof crdtuxp
  3415. *
  3416. * @returns {Promise<string>} file path
  3417. */
  3418. function getPluginInstallerPath() {
  3419. // coderstate: promisor
  3420. let retVal = RESOLVED_PROMISE_UNDEFINED;
  3421. do {
  3422. try {
  3423. const responsePromise =
  3424. evalTQL(
  3425. "getPluginInstallerPath()"
  3426. );
  3427. if (! responsePromise) {
  3428. break;
  3429. }
  3430. function evalTQLResolveFtn(response) {
  3431. // coderstate: resolver
  3432. let retVal;
  3433. do {
  3434. if (! response || response.error) {
  3435. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  3436. break;
  3437. }
  3438. retVal = response.text;
  3439. }
  3440. while (false);
  3441. return retVal;
  3442. };
  3443. function evalTQLRejectFtn(reason) {
  3444. // coderstate: rejector
  3445. crdtuxp.logError(arguments, "rejected for " + reason);
  3446. return undefined;
  3447. };
  3448. retVal = responsePromise.then(
  3449. evalTQLResolveFtn,
  3450. evalTQLRejectFtn
  3451. );
  3452. }
  3453. catch (err) {
  3454. crdtuxp.logError(arguments, "throws " + err);
  3455. }
  3456. }
  3457. while (false);
  3458. return retVal;
  3459. }
  3460. module.exports.getPluginInstallerPath = getPluginInstallerPath;
  3461. /**
  3462. * Internal function. Query the Tightener daemon for system information
  3463. *
  3464. * @function getSysInfo__
  3465. *
  3466. * @returns {object} system info
  3467. */
  3468. function getSysInfo__() {
  3469. // coderstate: promisor
  3470. let retVal = RESOLVED_PROMISE_UNDEFINED;
  3471. do {
  3472. try {
  3473. if (SYS_INFO) {
  3474. retVal = Promise.resolve(SYS_INFO);
  3475. break;
  3476. }
  3477. const responsePromise =
  3478. evalTQL(
  3479. "enquote(sysInfo())"
  3480. );
  3481. if (! responsePromise) {
  3482. break;
  3483. }
  3484. function evalTQLResolveFtn(response) {
  3485. // coderstate: resolver
  3486. let retVal;
  3487. do {
  3488. if (! response || response.error) {
  3489. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  3490. break;
  3491. }
  3492. let responseWrapperStr = response.text;
  3493. if (! responseWrapperStr) {
  3494. crdtuxp.logError(arguments, "no response text");
  3495. break;
  3496. }
  3497. let responseData = deQuote(responseWrapperStr);
  3498. if (! responseData) {
  3499. crdtuxp.logError(arguments, "no responseData");
  3500. break;
  3501. }
  3502. let responseStr = binaryUTF8ToStr(responseData);
  3503. if (! responseStr) {
  3504. crdtuxp.logError(arguments, "no responseStr");
  3505. break;
  3506. }
  3507. SYS_INFO = JSON.parse(responseStr);
  3508. retVal = SYS_INFO;
  3509. }
  3510. while (false);
  3511. return retVal;
  3512. };
  3513. function evalTQLRejectFtn(reason) {
  3514. // coderstate: rejector
  3515. crdtuxp.logError(arguments, "rejected for " + reason);
  3516. return undefined;
  3517. };
  3518. retVal = responsePromise.then(
  3519. evalTQLResolveFtn,
  3520. evalTQLRejectFtn
  3521. );
  3522. }
  3523. catch (err) {
  3524. crdtuxp.logError(arguments, "throws " + err);
  3525. }
  3526. }
  3527. while (false);
  3528. return retVal;
  3529. }
  3530. /**
  3531. * Interpret a string extracted from some INI data as a unit name
  3532. *
  3533. * @function getUnitFromINI
  3534. * @memberof crdtuxp
  3535. *
  3536. * @param {string} in_value - ini value
  3537. * @param {string} in_defaultUnit - default to use if no match is found
  3538. * @returns {string} value
  3539. */
  3540. function getUnitFromINI(in_value, in_defaultUnit) {
  3541. // coderstate: function
  3542. const defaultUnit = (in_defaultUnit !== undefined) ? in_defaultUnit : crdtuxp.UNIT_NAME_NONE;
  3543. let retVal = defaultUnit;
  3544. try {
  3545. const value = (in_value + "").replace(REGEXP_TRIM, REGEXP_TRIM_REPLACE).toLowerCase();
  3546. if (value == "\"" || value.substring(0,2) == "in") {
  3547. retVal = crdtuxp.UNIT_NAME_INCH;
  3548. }
  3549. else if (value == "cm" || value == "cms" || value.substr(0,4) == "cent") {
  3550. retVal = crdtuxp.UNIT_NAME_CM;
  3551. }
  3552. else if (value == "mm" || value == "mms" || value.substr(0,4) == "mill") {
  3553. retVal = crdtuxp.UNIT_NAME_MM;
  3554. }
  3555. else if (value.substring(0,3) == "cic") {
  3556. retVal = crdtuxp.UNIT_NAME_CICERO;
  3557. }
  3558. else if (value.substring(0,3) == "pic") {
  3559. retVal = crdtuxp.UNIT_NAME_PICA;
  3560. }
  3561. else if (value.substring(0,3) == "pix" || value == "px") {
  3562. retVal = crdtuxp.UNIT_NAME_PIXEL;
  3563. }
  3564. else if (value.substring(0,3) == "poi" || value == "pt") {
  3565. retVal = crdtuxp.UNIT_NAME_POINT;
  3566. }
  3567. }
  3568. catch (err) {
  3569. crdtuxp.logError(arguments, "throws " + err);
  3570. }
  3571. return retVal;
  3572. }
  3573. module.exports.getUnitFromINI = getUnitFromINI;
  3574. /**
  3575. * Get our bearings and figure out what operating system context we're operating in.
  3576. *
  3577. * @function getContext
  3578. * @memberof crdtuxp
  3579. *
  3580. * @returns {object} context
  3581. */
  3582. function getContext() {
  3583. // coderstate: function
  3584. let retVal;
  3585. do {
  3586. try {
  3587. // context can be pre-populated by a calling script, in which case we look if there is any missing
  3588. // data that we can add
  3589. let context = crdtuxp.context;
  3590. if (! context) {
  3591. context = {};
  3592. crdtuxp.context = context;
  3593. }
  3594. if (context.areDefaultGetContextPathsInitialized) {
  3595. retVal = context;
  3596. break;
  3597. }
  3598. context.areDefaultGetContextPathsInitialized = true;
  3599. let uxpContext = getUXPContext();
  3600. if (! context.PATH_HOME) {
  3601. context.PATH_HOME = uxpContext.os.homedir() + crdtuxp.path.SEPARATOR;
  3602. }
  3603. if (! context.PATH_DOCUMENTS) {
  3604. // This is an educated guess which will be correct most of the time
  3605. context.PATH_DOCUMENTS = context.PATH_HOME + "Documents" + crdtuxp.path.SEPARATOR;
  3606. }
  3607. if (! context.PATH_DESKTOP) {
  3608. // This is an educated guess which will be correct most of the time
  3609. context.PATH_DESKTOP = context.PATH_HOME + "Desktop" + crdtuxp.path.SEPARATOR;
  3610. }
  3611. if (! context.PATH_USERDATA) {
  3612. // This is an educated guess which will be correct most of the time
  3613. if (crdtuxp.IS_MAC) {
  3614. context.PATH_USERDATA = context.PATH_HOME + "Library/Application Support/";
  3615. }
  3616. else {
  3617. context.PATH_USERDATA = context.PATH_HOME + "AppData\\Roaming\\";
  3618. }
  3619. }
  3620. if (! context.PATH_TIGHTENER_STORAGE) {
  3621. context.PATH_TIGHTENER_STORAGE = context.PATH_USERDATA + "net.tightener" + crdtuxp.path.SEPARATOR;
  3622. }
  3623. if (! context.PATH_APP_STORAGE) {
  3624. context.PATH_APP_STORAGE = context.PATH_TIGHTENER_STORAGE + "Licensing" + crdtuxp.path.SEPARATOR;
  3625. }
  3626. if (! context.PATH_EVAL_TQL) {
  3627. context.PATH_EVAL_TQL = context.PATH_APP_STORAGE + "EvalTQL" + crdtuxp.path.SEPARATOR;
  3628. }
  3629. retVal = context;
  3630. }
  3631. catch (err) {
  3632. crdtuxp.logError(arguments, "throws " + err);
  3633. }
  3634. }
  3635. while (false);
  3636. return retVal;
  3637. }
  3638. module.exports.getContext = getContext;
  3639. /**
  3640. * Get our bearings and figure out what context we're operating in. Depending on the context<br>
  3641. * we will or won't have access to certain features
  3642. *
  3643. * @function getUXPContext
  3644. * @memberof crdtuxp
  3645. *
  3646. * @returns {object} context
  3647. */
  3648. function getUXPContext() {
  3649. // coderstate: function
  3650. let retVal;
  3651. do {
  3652. try {
  3653. if (crdtuxp.uxpContext) {
  3654. retVal = crdtuxp.uxpContext;
  3655. break;
  3656. }
  3657. let uxpContext = {};
  3658. crdtuxp.uxpContext = uxpContext;
  3659. uxpContext.fs = require("fs");
  3660. uxpContext.os = require("os");
  3661. uxpContext.uxp = require("uxp");
  3662. uxpContext.path = require("path");
  3663. let storage = uxpContext.uxp.storage;
  3664. uxpContext.lfs = storage.localFileSystem;
  3665. uxpContext.sessionID = window.crypto.randomUUID().replace(/-/g,"");
  3666. try {
  3667. // @ts-ignore
  3668. uxpContext.indesign = require("indesign");
  3669. uxpContext.app = uxpContext.indesign.app;
  3670. if (uxpContext.app.name.indexOf("Server") >= 0) {
  3671. uxpContext.uxpVariant = UXP_VARIANT_INDESIGN_SERVER_UXPSCRIPT;
  3672. uxpContext.hasDirectFileAccess = true;
  3673. uxpContext.hasNetworkAccess = true;
  3674. }
  3675. else {
  3676. uxpContext.uxpVariant = UXP_VARIANT_INDESIGN_UXPSCRIPT;
  3677. let commandId = uxpContext.uxp?.script?.executionContext?.commandInfo?._manifestCommand?.commandId;
  3678. if (commandId == "scriptMainCommand") {
  3679. uxpContext.uxpVariant = UXP_VARIANT_INDESIGN_UXPSCRIPT;
  3680. uxpContext.hasDirectFileAccess = true;
  3681. uxpContext.hasNetworkAccess = true;
  3682. }
  3683. else {
  3684. uxpContext.uxpVariant = UXP_VARIANT_INDESIGN_UXP;
  3685. uxpContext.hasDirectFileAccess = false;
  3686. uxpContext.hasNetworkAccess = true;
  3687. }
  3688. }
  3689. }
  3690. catch (err) {
  3691. crdtuxp.logTrace(arguments, "throws " + err);
  3692. }
  3693. try {
  3694. // @ts-ignore
  3695. uxpContext.photoshop = require("photoshop");
  3696. uxpContext.app = uxpContext.photoshop.app;
  3697. let commandId = uxpContext.uxp?.script?.executionContext?.commandInfo?._manifestCommand?.commandId;
  3698. if (commandId == "scriptMainCommand") {
  3699. uxpContext.uxpVariant = UXP_VARIANT_PHOTOSHOP_UXPSCRIPT;
  3700. uxpContext.hasDirectFileAccess = true;
  3701. uxpContext.hasNetworkAccess = false;
  3702. }
  3703. else {
  3704. uxpContext.uxpVariant = UXP_VARIANT_PHOTOSHOP_UXP;
  3705. uxpContext.hasDirectFileAccess = false;
  3706. uxpContext.hasNetworkAccess = true;
  3707. }
  3708. }
  3709. catch (err) {
  3710. crdtuxp.logTrace(arguments, "throws " + err);
  3711. }
  3712. retVal = uxpContext;
  3713. }
  3714. catch (err) {
  3715. crdtuxp.logError(arguments, "throws " + err);
  3716. }
  3717. }
  3718. while (false);
  3719. return retVal;
  3720. }
  3721. module.exports.getUXPContext = getUXPContext;
  3722. /**
  3723. * Hash some text
  3724. *
  3725. * Not cryptographic
  3726. *
  3727. * @function hashStringFNV1a
  3728. * @memberof crdtuxp
  3729. *
  3730. * @param {string} s - text to hash
  3731. * @returns a hash for the input
  3732. *
  3733. */
  3734. function hashStringFNV1a(s) {
  3735. const fnv1a = (str) => {
  3736. let hash = 0x811c9dc5; // 32-bit FNV-1a offset basis
  3737. for (let i = 0; i < str.length; i++) {
  3738. hash ^= str.charCodeAt(i);
  3739. hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
  3740. }
  3741. return hash >>> 0; // Ensure 32-bit unsigned
  3742. };
  3743. var hash = fnv1a(s.toString()).toString(16); // Hexadecimal hash
  3744. return hash;
  3745. }
  3746. module.exports.hashStringFNV1a = hashStringFNV1a;
  3747. /**
  3748. * Initialize crdtuxp
  3749. *
  3750. * @function init
  3751. * @memberof crdtuxp
  3752. *
  3753. * @returns {Promise<boolean|undefined>} when true: valid issuer has made CRDT_UXP extra features available
  3754. *
  3755. */
  3756. function init(context) {
  3757. // coderstate: promisor
  3758. let retVal = RESOLVED_PROMISE_UNDEFINED;
  3759. do {
  3760. try {
  3761. if (! crdtuxp.isProxyPromiseInjected) {
  3762. injectProxyPromiseClass();
  3763. }
  3764. if (! context) {
  3765. context = {};
  3766. }
  3767. if (! crdtuxp.context) {
  3768. crdtuxp.context = context;
  3769. }
  3770. else {
  3771. for (attr in context) {
  3772. crdtuxp.context[attr] = context[attr];
  3773. }
  3774. context = crdtuxp.context;
  3775. }
  3776. // Use crdtuxp.js as a reference point
  3777. // FILE_PATH_CRDT_UXP_JS is the path to crdtuxp.js
  3778. if (! context.FILE_PATH_CRDT_UXP_JS) {
  3779. context.FILE_PATH_CRDT_UXP_JS = crdtuxp.getCurrentScriptPath();
  3780. if (! context.FILE_PATH_CRDT_UXP_JS) {
  3781. consoleLog("context.FILE_PATH_CRDT_UXP_JS is not defined");
  3782. break;
  3783. }
  3784. }
  3785. // FILE_PATH_CRDT_UXP_FOLDER is the folder containing crdtuxp.js
  3786. if (! context.FILE_PATH_CRDT_UXP_FOLDER) {
  3787. context.FILE_PATH_CRDT_UXP_FOLDER =
  3788. crdtuxp.path.dirName(
  3789. context.FILE_PATH_CRDT_UXP_JS,
  3790. { addTrailingSeparator: true }
  3791. );
  3792. if (! context.FILE_PATH_CRDT_UXP_FOLDER) {
  3793. consoleLog("context.FILE_PATH_CRDT_UXP_FOLDER is not defined");
  3794. break;
  3795. }
  3796. }
  3797. // FILE_PATH_PROJECT_FOLDER is the folder containing the project
  3798. if (! context.FILE_PATH_PROJECT_FOLDER) {
  3799. if (context.PATH_LAUNCHER_SCRIPT_PARENT) {
  3800. context.FILE_PATH_PROJECT_FOLDER = context.PATH_LAUNCHER_SCRIPT_PARENT;
  3801. }
  3802. else {
  3803. context.FILE_PATH_PROJECT_FOLDER =
  3804. crdtuxp.path.dirName(
  3805. context.FILE_PATH_CRDT_UXP_FOLDER,
  3806. { addTrailingSeparator: true }
  3807. );
  3808. if (! context.FILE_PATH_PROJECT_FOLDER) {
  3809. consoleLog("context.FILE_PATH_PROJECT_FOLDER is not defined");
  3810. break;
  3811. }
  3812. }
  3813. }
  3814. // RUNPATH_ROOT is the path of the parent folder for the main script file,
  3815. // not of the PluginInstaller-generated wrapper launcher script file that
  3816. // might live in another folder
  3817. //
  3818. // FILE_PATH_ROOT is the absolute path that corresponds to RUNPATH_ROOT
  3819. //
  3820. // RUNPATH_ROOT can be used with require()
  3821. //
  3822. // FILE_PATH_ROOT can be used for crdtuxp.file... operations; it cannot be used with require()
  3823. if (! context.FILE_PATH_ROOT) {
  3824. context.FILE_PATH_ROOT = context.FILE_PATH_PROJECT_FOLDER;
  3825. }
  3826. //
  3827. // RUNPATH_ROOT is used with 'require' which in UXP does not accept absolute
  3828. // paths
  3829. //
  3830. if (! context.RUNPATH_ROOT) {
  3831. // Use slash separator - it's needed for require()
  3832. if (
  3833. context.FILE_PATH_ROOT
  3834. &&
  3835. context.FILE_PATH_PROJECT_FOLDER
  3836. &&
  3837. context.FILE_PATH_ROOT != context.FILE_PATH_PROJECT_FOLDER
  3838. ) {
  3839. let slashedFilePathRootResolved = context.FILEPath_ROOT.replace(/\\/g,"/");
  3840. let slashedFilePathProjectFolder = context.FILEPath_PROJECT_FOLDER.replace(/\\/g,"/");
  3841. context.RUNPATH_ROOT = crdtuxp.path.relativeTo(slashedFilePathRootResolved, slashedFilePathProjectFolder, "/")
  3842. }
  3843. else {
  3844. // If the two folder are the same, or one of them is not defined yet,
  3845. // use the current folder
  3846. context.RUNPATH_ROOT = "./";
  3847. }
  3848. }
  3849. if (! context.RUNPATH_CRDT_UXP) {
  3850. context.RUNPATH_CRDT_UXP = context.RUNPATH_ROOT + "/" + crdtuxp.path.baseName(context.FILE_PATH_CRDT_UXP_FOLDER);
  3851. }
  3852. if (context.ISSUER_GUID && context.ISSUER_EMAIL) {
  3853. retVal = crdtuxp.setIssuer(context.ISSUER_GUID, context.ISSUER_EMAIL);
  3854. }
  3855. else {
  3856. retVal = RESOLVED_PROMISE_TRUE;
  3857. }
  3858. }
  3859. catch (err) {
  3860. consoleLog("init throws " + err);
  3861. }
  3862. }
  3863. while (false);
  3864. return retVal;
  3865. }
  3866. module.exports.init = init;
  3867. /**
  3868. * Wrap the system <code>Promise</code> with a new <code>Promise</code> class that allows us to track pending promises
  3869. *
  3870. * @function injectProxyPromiseClass
  3871. * @memberof crdtuxp
  3872. */
  3873. function injectProxyPromiseClass() {
  3874. // coderstate: procedure
  3875. try {
  3876. // Save the original Promise class
  3877. const SystemPromise = global.Promise;
  3878. let PROMISES_PENDING = {};
  3879. let LAST_PROMISE_UNIQUE_ID = 0;
  3880. crdtuxp.isProxyPromiseInjected = true;
  3881. // Define the new Promise class
  3882. class Promise {
  3883. constructor(executor) {
  3884. let curThis = this;
  3885. curThis._state = 'pending';
  3886. curThis._value = undefined;
  3887. curThis._id = ++LAST_PROMISE_UNIQUE_ID;
  3888. PROMISES_PENDING[curThis._id] = curThis;
  3889. // Create a new instance of the original Promise
  3890. this._promise = new SystemPromise((resolve, reject) => {
  3891. executor(
  3892. (value) => {
  3893. curThis._state = 'resolved';
  3894. curThis._value = value;
  3895. curThis.untracked();
  3896. resolve(value);
  3897. },
  3898. (reason) => {
  3899. curThis._state = 'rejected';
  3900. curThis._value = reason;
  3901. curThis.untracked();
  3902. reject(reason);
  3903. });
  3904. });
  3905. }
  3906. // Proxy static methods
  3907. static pendingPromises() {
  3908. // coderstate: function
  3909. let retVal = [];
  3910. for (let id in PROMISES_PENDING) {
  3911. let promise = PROMISES_PENDING[id];
  3912. if (promise._state == 'pending') {
  3913. retVal.push(promise);
  3914. }
  3915. }
  3916. return retVal;
  3917. }
  3918. static finalizePromises() {
  3919. // coderstate: promisor
  3920. function finalizeExecutorFtn(resolveFtn, rejectFtn) {
  3921. setImmediate(
  3922. () => {
  3923. let retVal;
  3924. let pendingPromises = Promise.pendingPromises();
  3925. if (pendingPromises.length == 0) {
  3926. resolveFtn();
  3927. }
  3928. else {
  3929. retVal = Promise.allSettled(pendingPromises).then(
  3930. () => {
  3931. // coderstate: resolver
  3932. return Promise.finalizePromises().
  3933. then(resolveFtn, rejectFtn);
  3934. },
  3935. (reason) => {
  3936. // coderstate: rejector
  3937. return Promise.finalizePromises().
  3938. then(resolveFtn, rejectFtn);
  3939. }
  3940. );
  3941. }
  3942. return retVal;
  3943. }
  3944. );
  3945. }
  3946. let finalizingPromise = new Promise(finalizeExecutorFtn);
  3947. finalizingPromise.untracked();
  3948. return finalizingPromise;
  3949. }
  3950. static resolve(value) {
  3951. return new Promise((resolve) => resolve(value));
  3952. }
  3953. static reject(reason) {
  3954. return new Promise((_, reject) => reject(reason));
  3955. }
  3956. static all(promises) {
  3957. return SystemPromise.all(promises);
  3958. }
  3959. static allSettled(promises) {
  3960. return SystemPromise.allSettled(promises)
  3961. }
  3962. static race(promises) {
  3963. return SystemPromise.race(promises);
  3964. }
  3965. // Proxy instance methods
  3966. then(onFulfilled, onRejected) {
  3967. return this._promise.then(onFulfilled, onRejected);
  3968. }
  3969. untracked() {
  3970. if (this._id in PROMISES_PENDING) {
  3971. delete PROMISES_PENDING[this._id];
  3972. }
  3973. }
  3974. catch(onRejected) {
  3975. return this._promise.catch(onRejected);
  3976. }
  3977. finally(onFinally) {
  3978. return this._promise.finally(onFinally);
  3979. }
  3980. isPending() {
  3981. return this._state === 'pending';
  3982. }
  3983. isResolved() {
  3984. return this._state === 'resolved';
  3985. }
  3986. isRejected() {
  3987. return this._state === 'rejected';
  3988. }
  3989. getValue() {
  3990. return this._value;
  3991. }
  3992. }
  3993. global.Promise = Promise;
  3994. }
  3995. catch (err) {
  3996. consoleLog("injectProxyPromiseClass throws " + err);
  3997. }
  3998. }
  3999. module.exports.injectProxyPromiseClass = injectProxyPromiseClass;
  4000. /**
  4001. * Calculate an integer power of an int value. Avoids using floating point, so should not have any floating-point<br>
  4002. * round-off errors. <code>Math.pow()</code> will probably give the exact same result, but I am doubtful that some<br>
  4003. * implementations might internally use <code>log</code> and <code>exp</code> to handle <code>Math.pow()</code>
  4004. *
  4005. * @function intPow
  4006. * @memberof crdtuxp
  4007. *
  4008. * @param {number} i - Integer base
  4009. * @param {number} intPower - integer power
  4010. * @returns {number|undefined} i ^ intPower
  4011. */
  4012. function intPow(i, intPower) {
  4013. // coderstate: function
  4014. let retVal;
  4015. do {
  4016. try {
  4017. if (Math.floor(intPower) != intPower) {
  4018. // Must be integer
  4019. retVal = undefined;
  4020. break;
  4021. }
  4022. if (intPower == 0) {
  4023. // Handle power of 0: 0^0 is not a number
  4024. if (i == 0) {
  4025. retVal = NaN;
  4026. }
  4027. else {
  4028. retVal = 1;
  4029. }
  4030. break;
  4031. }
  4032. if (intPower > 0 && i == 0) {
  4033. retVal = 0;
  4034. break;
  4035. }
  4036. if (intPower < 0 && i == 0) {
  4037. retVal = NaN;
  4038. break;
  4039. }
  4040. if (i == 1) {
  4041. // Multiplying 1 with itself is 1
  4042. retVal = 1;
  4043. break;
  4044. }
  4045. if (intPower == 1) {
  4046. // i ^ 1 is i
  4047. retVal = i;
  4048. break;
  4049. }
  4050. if (intPower < 0) {
  4051. // i^-x is 1/(i^x)
  4052. let intermediate = intPow(i, -intPower);
  4053. if (intermediate) {
  4054. retVal = 1 / intermediate;
  4055. }
  4056. break;
  4057. }
  4058. // Divide and conquer
  4059. const halfIntPower = intPower >> 1;
  4060. const otherHalfIntPower = intPower - halfIntPower;
  4061. const part1 = intPow(i, halfIntPower);
  4062. if (! part1) {
  4063. break;
  4064. }
  4065. let part2;
  4066. if (halfIntPower == otherHalfIntPower) {
  4067. part2 = part1;
  4068. }
  4069. else {
  4070. part2 = intPow(i, otherHalfIntPower);
  4071. if (! part2) {
  4072. break;
  4073. }
  4074. }
  4075. retVal = part1 * part2;
  4076. }
  4077. catch (err) {
  4078. crdtuxp.logError(arguments, "throws " + err);
  4079. }
  4080. }
  4081. while (false);
  4082. return retVal;
  4083. }
  4084. module.exports.intPow = intPow;
  4085. /**
  4086. * Check if the daemon is running.
  4087. *
  4088. * @function isDaemonResponsive
  4089. * @memberof crdtuxp
  4090. *
  4091. * @returns {Promise<boolean|undefined>} is the Creative Developer Tools daemon responsive?
  4092. */
  4093. function isDaemonResponsive() {
  4094. // coderstate: promisor
  4095. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4096. do {
  4097. try {
  4098. const options = {
  4099. waitFileTimeout: RESPONSE_CHECK_FILE_TIMEOUT_MILLISECONDS,
  4100. waitFileCheckInterval: RESPONSE_CHECK_FILE_INTERVAL_MILLISECONDS
  4101. };
  4102. const isDaemonResponsivePromise =
  4103. evalTQL(
  4104. "'OK'",
  4105. options);
  4106. if (! isDaemonResponsivePromise) {
  4107. break;
  4108. }
  4109. function evalTQLResolveFtn(response) {
  4110. // coderstate: resolver
  4111. let retVal;
  4112. do {
  4113. if (! response || response.error) {
  4114. retVal = false;
  4115. break;
  4116. }
  4117. retVal = response.text == "OK";
  4118. }
  4119. while (false);
  4120. return retVal;
  4121. };
  4122. function evalTQLRejectFtn(reason) {
  4123. // coderstate: rejector
  4124. consoleLog(arguments, "rejected for " + reason);
  4125. return false;
  4126. };
  4127. retVal = isDaemonResponsivePromise.then(
  4128. evalTQLResolveFtn,
  4129. evalTQLRejectFtn
  4130. );
  4131. }
  4132. catch (err) {
  4133. consoleLog(arguments, "throws " + err);
  4134. }
  4135. }
  4136. while (false);
  4137. return retVal;
  4138. }
  4139. module.exports.isDaemonResponsive = isDaemonResponsive;
  4140. /**
  4141. * Extend or shorten a string to an exact length, adding <code>padChar</code> as needed
  4142. *
  4143. * @function leftPad
  4144. * @memberof crdtuxp
  4145. *
  4146. * @param {string} s - string to be extended or shortened
  4147. * @param {string} padChar - string to append repeatedly if length needs to extended
  4148. * @param {number} len - desired result length
  4149. * @returns {string} padded or shortened string
  4150. */
  4151. function leftPad(s, padChar, len) {
  4152. // coderstate: function
  4153. let retVal = "";
  4154. do {
  4155. try {
  4156. retVal = s + "";
  4157. if (retVal.length == len) {
  4158. break;
  4159. }
  4160. if (retVal.length > len) {
  4161. retVal = retVal.substring(retVal.length - len);
  4162. break;
  4163. }
  4164. const padLength = len - retVal.length;
  4165. const padding = new Array(padLength + 1).join(padChar)
  4166. retVal = padding + retVal;
  4167. }
  4168. catch (err) {
  4169. crdtuxp.logError(arguments, "throws " + err);
  4170. }
  4171. }
  4172. while (false);
  4173. return retVal;
  4174. }
  4175. module.exports.leftPad = leftPad;
  4176. /**
  4177. * Make a log entry of the call of a function. Pass in the <code>arguments</code> keyword as a parameter.
  4178. *
  4179. * @function logEntry
  4180. * @memberof crdtuxp
  4181. *
  4182. * @param {array} reportingFunctionArguments - pass in the current <code>arguments</code> to the function. This is used to determine the function's name for the log
  4183. * @returns {Promise} - a promise that can be used to await the log call completion
  4184. */
  4185. function logEntry(reportingFunctionArguments) {
  4186. // coderstate: promisor
  4187. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4188. if (LOG_ENTRY_EXIT) {
  4189. retVal = logTrace(reportingFunctionArguments, "Entry");
  4190. }
  4191. return retVal;
  4192. }
  4193. module.exports.logEntry = logEntry;
  4194. /**
  4195. * Make a log entry of an error message. Pass in the <code>arguments</code> keyword as the first parameter<br>
  4196. * If the error level is below <code>crdtuxp.LOG_LEVEL_ERROR</code> nothing happens
  4197. *
  4198. * @function logError
  4199. * @memberof crdtuxp
  4200. *
  4201. * @param {any} reportingFunctionArguments - pass in the current <code>arguments</code> to the function.<br>
  4202. * This is used to determine the function's name for the log
  4203. * @param {any} message - error message
  4204. * @returns {Promise} - a promise that can be used to await the log call completion
  4205. */
  4206. function logError(reportingFunctionArguments, message) {
  4207. // coderstate: promisor
  4208. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4209. if (LOG_LEVEL >= LOG_LEVEL_ERROR) {
  4210. if (! message) {
  4211. message = reportingFunctionArguments;
  4212. reportingFunctionArguments = undefined;
  4213. }
  4214. retVal = logMessage(reportingFunctionArguments, LOG_LEVEL_ERROR, message);
  4215. }
  4216. return retVal;
  4217. }
  4218. module.exports.logError = logError;
  4219. /**
  4220. * Make a log entry of the exit of a function. Pass in the <code>arguments</code> keyword as a parameter.
  4221. *
  4222. * @function logExit
  4223. * @memberof crdtuxp
  4224. *
  4225. * @param {any} reportingFunctionArguments - pass in the current <code>arguments</code> to the function. <br>
  4226. * This is used to determine the function's name for the log
  4227. * @returns {Promise} - a promise that can be used to await the log call completion
  4228. */
  4229. function logExit(reportingFunctionArguments) {
  4230. // coderstate: promisor
  4231. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4232. if (LOG_ENTRY_EXIT) {
  4233. retVal = logTrace(reportingFunctionArguments, "Exit");
  4234. }
  4235. return retVal;
  4236. }
  4237. module.exports.logExit = logExit;
  4238. /**
  4239. * Output a log message. Pass in the <code>arguments</code> keyword as the first parameter.
  4240. *
  4241. * @function logMessage
  4242. * @memberof crdtuxp
  4243. *
  4244. * @param {any} reportingFunctionArguments - pass in the current <code>arguments</code> to the function.<br>
  4245. * This is used to determine the function's name for the log
  4246. * @param {number} logLevel - log level 0 - 4
  4247. * @param {string} message - the note to output
  4248. * @returns {Promise} - a promise that can be used to await the log call completion
  4249. */
  4250. function logMessage(reportingFunctionArguments, logLevel, message) {
  4251. // coderstate: promisor
  4252. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4253. let savedInLogger = IN_LOGGER;
  4254. do {
  4255. try {
  4256. IN_LOGGER = true;
  4257. let functionPrefix = "";
  4258. let functionName = "";
  4259. if (! message) {
  4260. message = reportingFunctionArguments;
  4261. reportingFunctionArguments = undefined;
  4262. }
  4263. else if (reportingFunctionArguments) {
  4264. if ("string" == typeof reportingFunctionArguments) {
  4265. functionName = reportingFunctionArguments;
  4266. }
  4267. else {
  4268. functionName = functionNameFromArguments(reportingFunctionArguments);
  4269. }
  4270. functionPrefix += functionName + ": ";
  4271. }
  4272. let now = new Date();
  4273. let timePrefix =
  4274. leftPad("" + now.getUTCDate(), "0", 2) +
  4275. "-" +
  4276. leftPad("" + (now.getUTCMonth() + 1), "0", 2) +
  4277. "-" +
  4278. leftPad("" + now.getUTCFullYear(), "0", 4) +
  4279. " " +
  4280. leftPad("" + now.getUTCHours(), "0", 2) +
  4281. ":" +
  4282. leftPad("" + now.getUTCMinutes(), "0", 2) +
  4283. ":" +
  4284. leftPad("" + now.getUTCSeconds(), "0", 2) +
  4285. "+00 ";
  4286. let platformPrefix = "U ";
  4287. let logLevelPrefix = "";
  4288. switch (logLevel) {
  4289. case LOG_LEVEL_ERROR:
  4290. logLevelPrefix = "ERROR";
  4291. break;
  4292. case LOG_LEVEL_WARNING:
  4293. logLevelPrefix = "WARN ";
  4294. break;
  4295. case LOG_LEVEL_NOTE:
  4296. logLevelPrefix = "NOTE ";
  4297. break;
  4298. case LOG_LEVEL_TRACE:
  4299. logLevelPrefix = "TRACE";
  4300. break;
  4301. default:
  4302. logLevelPrefix = " ";
  4303. break;
  4304. }
  4305. let logLine = platformPrefix + timePrefix + "- " + logLevelPrefix + ": " + functionPrefix + message;
  4306. let uxpContext = getUXPContext();
  4307. if (LOG_TO_UXPDEVTOOL_CONSOLE) {
  4308. consoleLog(logLine);
  4309. }
  4310. else {
  4311. if (SYNC_LOG_TO_FILE_PATH) {
  4312. fileAppend_(SYNC_LOG_TO_FILE_PATH, logLine + "\n");
  4313. }
  4314. }
  4315. if (savedInLogger) {
  4316. // Don't try to use async stuff when nested in logger
  4317. break;
  4318. }
  4319. // Only wait for it to resolve if we have network access
  4320. // Otherwise logging slows down to a crawl because of the polling
  4321. // mechanism used to communicate with the daemon
  4322. let waitForLogConfirmation;
  4323. if (uxpContext && uxpContext.hasNetworkAccess) {
  4324. waitForLogConfirmation = true;
  4325. }
  4326. let evalTQLOptions = {
  4327. wait: waitForLogConfirmation,
  4328. fromLogger: true
  4329. };
  4330. let promises = [];
  4331. if (LOG_TO_CRDT) {
  4332. let logCRDTPromise =
  4333. evalTQL(
  4334. "logMessage(" +
  4335. logLevel + "," +
  4336. dQ(functionName) + "," +
  4337. dQ(message) +
  4338. ")",
  4339. evalTQLOptions
  4340. );
  4341. if (waitForLogConfirmation) {
  4342. promises.push(logCRDTPromise);
  4343. }
  4344. }
  4345. if (LOG_TO_FILE_PATH) {
  4346. let appendPromise =
  4347. fileAppendString(
  4348. LOG_TO_FILE_PATH,
  4349. logLine + "\n",
  4350. evalTQLOptions);
  4351. if (waitForLogConfirmation) {
  4352. promises.push(appendPromise);
  4353. }
  4354. }
  4355. if (promises.length) {
  4356. retVal = Promise.all(promises);
  4357. }
  4358. }
  4359. catch (err) {
  4360. }
  4361. }
  4362. while (false);
  4363. IN_LOGGER = savedInLogger;
  4364. return retVal;
  4365. }
  4366. module.exports.logMessage = logMessage;
  4367. /**
  4368. * Make a log entry of a note. Pass in the <code>arguments</code> keyword as the first parameter.<br>
  4369. * If the error level is below <code>crdtuxp.LOG_LEVEL_NOTE</code> nothing happens
  4370. *
  4371. * @function logNote
  4372. * @memberof crdtuxp
  4373. *
  4374. * @param {any} reportingFunctionArguments - pass in the current <code>arguments</code> to the function.<br>
  4375. * This is used to determine the function's name for the log
  4376. * @param {any} message - the note to output
  4377. * @returns {Promise} - a promise that can be used to await the log call completion
  4378. */
  4379. function logNote(reportingFunctionArguments, message) {
  4380. // coderstate: promisor
  4381. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4382. if (LOG_LEVEL >= LOG_LEVEL_NOTE) {
  4383. if (! message) {
  4384. message = reportingFunctionArguments;
  4385. reportingFunctionArguments = undefined;
  4386. }
  4387. retVal = logMessage(reportingFunctionArguments, LOG_LEVEL_NOTE, message);
  4388. }
  4389. return retVal;
  4390. }
  4391. module.exports.logNote = logNote;
  4392. /**
  4393. * Emit a trace messsage into the log. Pass in the <code>arguments</code> keyword as the first parameter.<br>
  4394. * If the error level is below <code>crdtuxp.LOG_LEVEL_TRACE</code> nothing happens
  4395. *
  4396. * @function logTrace
  4397. * @memberof crdtuxp
  4398. *
  4399. * @param {any} reportingFunctionArguments - pass in the current <code>arguments</code> to the function.<br>
  4400. * This is used to determine the function's name for the log
  4401. * @param {any} message - the trace message to output
  4402. * @returns {Promise} - a promise that can be used to await the log call completion
  4403. */
  4404. function logTrace(reportingFunctionArguments, message) {
  4405. // coderstate: promisor
  4406. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4407. if (LOG_LEVEL >= LOG_LEVEL_TRACE) {
  4408. if (! message) {
  4409. message = reportingFunctionArguments;
  4410. reportingFunctionArguments = undefined;
  4411. }
  4412. retVal = logMessage(reportingFunctionArguments, LOG_LEVEL_TRACE, message);
  4413. }
  4414. return retVal;
  4415. }
  4416. module.exports.logTrace = logTrace;
  4417. /**
  4418. * Emit a warning messsage into the log. Pass in the <code>arguments</code> keyword as the first parameter.<br>
  4419. * If the error level is below <code>crdtuxp.LOG_LEVEL_WARNING</code> nothing happens
  4420. *
  4421. * @function logWarning
  4422. * @memberof crdtuxp
  4423. *
  4424. * @param {any} reportingFunctionArguments - pass in the current <code>arguments</code> to the function.<br>
  4425. * This is used to determine the function's name for the log
  4426. * @param {any} message - the warning message to output
  4427. */
  4428. function logWarning(reportingFunctionArguments, message) {
  4429. // coderstate: promisor
  4430. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4431. if (LOG_LEVEL >= LOG_LEVEL_WARNING) {
  4432. if (! message) {
  4433. message = reportingFunctionArguments;
  4434. reportingFunctionArguments = undefined;
  4435. }
  4436. retVal = logMessage(reportingFunctionArguments, LOG_LEVEL_WARNING, message);
  4437. }
  4438. return retVal;
  4439. }
  4440. module.exports.logWarning = logWarning;
  4441. /**
  4442. * The unique <code>GUID</code> of this computer<br>
  4443. * <br>
  4444. * Only available to paid developer accounts
  4445. *
  4446. * @function machineGUID
  4447. * @memberof crdtuxp
  4448. *
  4449. * @returns {Promise<string | undefined>} a <code>GUID</code> string
  4450. */
  4451. function machineGUID() {
  4452. // coderstate: promisor
  4453. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4454. do {
  4455. try {
  4456. const responsePromise =
  4457. evalTQL(
  4458. "machineGUID()"
  4459. );
  4460. if (! responsePromise) {
  4461. break;
  4462. }
  4463. function evalTQLResolveFtn(response) {
  4464. // coderstate: resolver
  4465. let retVal;
  4466. do {
  4467. if (! response || response.error) {
  4468. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  4469. break;
  4470. }
  4471. retVal = response.text;
  4472. }
  4473. while (false);
  4474. return retVal;
  4475. };
  4476. function evalTQLRejectFtn(reason) {
  4477. // coderstate: rejector
  4478. crdtuxp.logError(arguments, "rejected for " + reason);
  4479. return undefined;
  4480. };
  4481. retVal = responsePromise.then(
  4482. evalTQLResolveFtn,
  4483. evalTQLRejectFtn
  4484. );
  4485. }
  4486. catch (err) {
  4487. crdtuxp.logError(arguments, "throws " + err);
  4488. }
  4489. }
  4490. while (false);
  4491. return retVal;
  4492. }
  4493. module.exports.machineGUID = machineGUID;
  4494. /**
  4495. * Launch the PluginInstaller if it is installed and configured
  4496. *
  4497. * @function pluginInstaller
  4498. * @memberof crdtuxp
  4499. *
  4500. * @returns {Promise<boolean|undefined>} success or failure
  4501. */
  4502. function pluginInstaller() {
  4503. // coderstate: promisor
  4504. let retVal = RESOLVED_PROMISE_UNDEFINED;
  4505. do {
  4506. try {
  4507. const responsePromise =
  4508. evalTQL(
  4509. "pluginInstaller() ? \"true\" : \"false\""
  4510. );
  4511. if (! responsePromise) {
  4512. break;
  4513. }
  4514. function evalTQLResolveFtn(response) {
  4515. // coderstate: resolver
  4516. let retVal;
  4517. do {
  4518. if (! response || response.error) {
  4519. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  4520. break;
  4521. }
  4522. retVal = response.text == "true";
  4523. }
  4524. while (false);
  4525. return retVal;
  4526. };
  4527. function evalTQLRejectFtn(reason) {
  4528. // coderstate: rejector
  4529. crdtuxp.logError(arguments, "rejected for " + reason);
  4530. return undefined;
  4531. };
  4532. retVal = responsePromise.then(
  4533. evalTQLResolveFtn,
  4534. evalTQLRejectFtn
  4535. );
  4536. }
  4537. catch (err) {
  4538. crdtuxp.logError(arguments, "throws " + err);
  4539. }
  4540. }
  4541. while (false);
  4542. return retVal;
  4543. }
  4544. module.exports.pluginInstaller = pluginInstaller;
  4545. /**
  4546. * Restore the log level to what it was when pushLogLevel was called
  4547. *
  4548. * @function popLogLevel
  4549. * @memberof crdtuxp
  4550. *
  4551. * @returns {number} log level that was popped off the stack
  4552. */
  4553. function popLogLevel() {
  4554. // coderstate: function
  4555. let retVal;
  4556. retVal = LOG_LEVEL;
  4557. if (LOG_LEVEL_STACK.length > 0) {
  4558. LOG_LEVEL = LOG_LEVEL_STACK.pop();
  4559. }
  4560. else {
  4561. LOG_LEVEL = LOG_LEVEL_OFF;
  4562. }
  4563. return retVal;
  4564. }
  4565. module.exports.popLogLevel = popLogLevel;
  4566. /**
  4567. * Convert a callback-based function into a Promise
  4568. *
  4569. * @function promisify
  4570. * @memberof crdtuxp
  4571. *
  4572. * @param {function} ftn - callback-based function
  4573. * @returns {function} promisified function
  4574. */
  4575. function promisify(ftn) {
  4576. // coderstate: function
  4577. return (...args) => {
  4578. return new Promise(
  4579. function executorFtn(resolveFtn, rejectFtn) {
  4580. // coderstate: executor
  4581. args.push(
  4582. (err, ...results) => {
  4583. if (err) {
  4584. return rejectFtn(err)
  4585. }
  4586. return resolveFtn(results.length === 1 ? results[0] : results);
  4587. }
  4588. );
  4589. ftn.call(this, ...args)
  4590. })
  4591. }
  4592. }
  4593. module.exports.promisify = promisify;
  4594. /**
  4595. * Convert a callback-based member function into a Promise
  4596. *
  4597. * @function promisifyWithContext
  4598. * @memberof crdtuxp
  4599. *
  4600. * @param {function} ftn - callback-based function
  4601. * @param {object} context - A context for the callback
  4602. * @returns {function} promisified function
  4603. */
  4604. function promisifyWithContext(ftn, context) {
  4605. // coderstate: function
  4606. return (...args) => {
  4607. return new Promise(
  4608. function executorFtn(resolveFtn, rejectFtn) {
  4609. // coderstate: executor
  4610. args.push(
  4611. (err, ...results) => {
  4612. if (err) {
  4613. return rejectFtn(err)
  4614. }
  4615. return resolveFtn(results.length === 1 ? results[0] : results);
  4616. }
  4617. );
  4618. ftn.call(context, ...args)
  4619. })
  4620. }
  4621. }
  4622. module.exports.promisifyWithContext = promisifyWithContext;
  4623. /**
  4624. * Save the previous log level and set a new log level
  4625. *
  4626. * @function pushLogLevel
  4627. * @memberof crdtuxp
  4628. *
  4629. * @param {number} newLogLevel - new log level to set
  4630. * @returns {number} previous log level
  4631. */
  4632. function pushLogLevel(newLogLevel) {
  4633. // coderstate: function
  4634. let retVal;
  4635. retVal = LOG_LEVEL;
  4636. LOG_LEVEL_STACK.push(LOG_LEVEL);
  4637. LOG_LEVEL = newLogLevel;
  4638. return retVal;
  4639. }
  4640. module.exports.pushLogLevel = pushLogLevel;
  4641. /**
  4642. * Make a 'fake string' into a byte array. Not UTF8-aware
  4643. *
  4644. * @function rawStringToByteArray
  4645. * @memberof crdtuxp
  4646. *
  4647. * @param {string} in_str - a raw string (possibly invalid UTF-8)
  4648. * @returns {array|undefined} an array of bytes
  4649. */
  4650. function rawStringToByteArray(in_str) {
  4651. // coderstate: function
  4652. let retVal = [];
  4653. try {
  4654. for (let idx = 0; idx < in_str.length; idx++) {
  4655. let c = in_str.charCodeAt(idx);
  4656. if (c > 255) {
  4657. retVal = undefined;
  4658. break;
  4659. }
  4660. retVal.push(c);
  4661. }
  4662. }
  4663. catch (err) {
  4664. crdtuxp.logError(arguments, "throws " + err);
  4665. }
  4666. return retVal;
  4667. }
  4668. module.exports.rawStringToByteArray = rawStringToByteArray;
  4669. /**
  4670. * Read a bunch of text and try to extract structured information in .INI format<br>
  4671. * <br>
  4672. * This function is lenient and is able to extract slightly mangled INI data from the text frame<br>
  4673. * content of an InDesign text frame.<br>
  4674. * <br>
  4675. * This function knows how to handle curly quotes should they be present.<br>
  4676. * <br>
  4677. * The following flexibilities have been built-in:<br>
  4678. * <br>
  4679. * - Attribute names are case-insensitive and anything not <code>a-z 0-9</code> is ignored.<br>
  4680. * Entries like <code>this or that = ...</code> or <code>thisOrThat = ...</code> or <code>this'orThat = ...</code> are<br>
  4681. * all equivalent. Only letters and digits are retained, and converted to lowercase.<br>
  4682. * <br>
  4683. * - Attribute values can be quoted with either single, double, curly quotes.<br>
  4684. * This often occurs because InDesign can be configured to convert normal quotes into<br>
  4685. * curly quotes automatically.<br>
  4686. * Attribute values without quotes are trimmed (e.g. <code>bla = x </code> is the same as <code>bla=x</code>)<br>
  4687. * Spaces are retained in quoted attribute values.<br>
  4688. * <br>
  4689. * - Any text will be ignore if not properly formatted as either a section name or an attribute-value<br>
  4690. * pair with an equal sign<br>
  4691. * <br>
  4692. * - Hard and soft returns are equivalent<br>
  4693. * <br>
  4694. * The return value is an object with the section names at the top level, and attribute names<br>
  4695. * below that. The following .INI<br>
  4696. * <code><br>
  4697. * [My data]<br>
  4698. * this is = " abc "<br>
  4699. * that = abc<br>
  4700. * </code><br>
  4701. * returns<br>
  4702. * <code><br>
  4703. * {<br>
  4704. * "mydata": {<br>
  4705. * "__rawSectionName": "My data",<br>
  4706. * "thisis": " abc ",<br>
  4707. * "that": "abc"<br>
  4708. * }<br>
  4709. * }<br>
  4710. * </code><br>
  4711. * Duplicated sections and entries are automatically suffixed with a counter suffix - e.g.<br>
  4712. * <code><br>
  4713. * [main]<br>
  4714. * a=1<br>
  4715. * a=2<br>
  4716. * a=3<br>
  4717. * </code><br>
  4718. * is equivalent with<br>
  4719. * <code><br>
  4720. * [main]<br>
  4721. * a=1<br>
  4722. * a_2=2<br>
  4723. * a_3=3<br>
  4724. * </code><br>
  4725. * and<br>
  4726. * <code><br>
  4727. * [a]<br>
  4728. * a=1<br>
  4729. * [a]<br>
  4730. * a=2<br>
  4731. * </code><br>
  4732. * is equivalent with
  4733. * <code><br>
  4734. * [a]<br>
  4735. * a=1<br>
  4736. * [a_2]<br>
  4737. * a=2<br>
  4738. * </code><br>
  4739. *
  4740. * @function readINI
  4741. * @memberof crdtuxp
  4742. *
  4743. * @param {string} in_text - raw text, which might or might not contain some INI-formatted data mixed with normal text
  4744. * @returns {object} either the ini data or <code>undefined</code>.
  4745. */
  4746. function readINI(in_text) {
  4747. // coderstate: function
  4748. let retVal = undefined;
  4749. do {
  4750. try {
  4751. if (! in_text) {
  4752. break;
  4753. }
  4754. if ("string" != typeof in_text) {
  4755. break;
  4756. }
  4757. let text = in_text + "\r";
  4758. let state = STATE_IDLE;
  4759. let attr = "";
  4760. let value = "";
  4761. let attrSpaceCount = 0;
  4762. let rawSectionName = "";
  4763. let sectionName = "";
  4764. let section = undefined;
  4765. let attrCounters = {};
  4766. let sectionCounters = {};
  4767. for (let idx = 0; state != STATE_ERROR && idx < text.length; idx++) {
  4768. const c = text.charAt(idx);
  4769. switch (state) {
  4770. default:
  4771. state = STATE_ERROR;
  4772. break;
  4773. case STATE_IDLE:
  4774. if (c == '[') {
  4775. state = STATE_SEEN_OPEN_SQUARE_BRACKET;
  4776. rawSectionName = "";
  4777. }
  4778. else if (c == '#') {
  4779. state = STATE_IN_COMMENT;
  4780. }
  4781. else if (c > ' ') {
  4782. attr = c;
  4783. attrSpaceCount = 0;
  4784. state = STATE_SEEN_NON_WHITE;
  4785. }
  4786. break;
  4787. case STATE_IN_COMMENT:
  4788. case STATE_SEEN_CLOSE_SQUARE_BRACKET:
  4789. if (c == '\r' || c == '\n') {
  4790. state = STATE_IDLE;
  4791. }
  4792. break;
  4793. case STATE_SEEN_OPEN_SQUARE_BRACKET:
  4794. if (c == ']') {
  4795. state = STATE_SEEN_CLOSE_SQUARE_BRACKET;
  4796. sectionName = rawSectionName.toLowerCase();
  4797. sectionName = sectionName.replace(REGEXP_DESPACE, REGEXP_DESPACE_REPLACE);
  4798. sectionName = sectionName.replace(REGEXP_SECTION_NAME_ONLY, REGEXP_SECTION_NAME_ONLY_REPLACE);
  4799. if (sectionName) {
  4800. if (! retVal) {
  4801. retVal = {};
  4802. }
  4803. let sectionSuffix = "";
  4804. let sectionCounter = 1;
  4805. if (sectionName in sectionCounters) {
  4806. sectionCounter = sectionCounters[sectionName];
  4807. sectionCounter++;
  4808. sectionSuffix = "_" + sectionCounter;
  4809. }
  4810. sectionCounters[sectionName] = sectionCounter;
  4811. sectionName += sectionSuffix;
  4812. section = {};
  4813. retVal[sectionName] = section;
  4814. // @ts-ignore
  4815. section.__rawSectionName = rawSectionName;
  4816. attrCounters = {};
  4817. }
  4818. }
  4819. else {
  4820. rawSectionName += c;
  4821. }
  4822. break;
  4823. case STATE_SEEN_NON_WHITE:
  4824. if (c == "=") {
  4825. value = "";
  4826. state = STATE_SEEN_EQUAL;
  4827. }
  4828. else if (c == '\r' || c == '\n') {
  4829. state = STATE_IDLE;
  4830. }
  4831. else if (c != " ") {
  4832. while (attrSpaceCount > 0) {
  4833. attr += " ";
  4834. attrSpaceCount--;
  4835. }
  4836. attr += c;
  4837. }
  4838. else {
  4839. attrSpaceCount++;
  4840. }
  4841. break;
  4842. case STATE_SEEN_EQUAL:
  4843. if (c != '\r' && c != '\n') {
  4844. value += c;
  4845. }
  4846. else {
  4847. value = value.replace(REGEXP_TRIM, REGEXP_TRIM_REPLACE);
  4848. if (value.length >= 2) {
  4849. let firstChar = value.charAt(0);
  4850. let lastChar = value.charAt(value.length - 1);
  4851. if (
  4852. (firstChar == "\"" || firstChar == "“" || firstChar == "”")
  4853. &&
  4854. (lastChar == "\"" || lastChar == "“" || lastChar == "”")
  4855. ) {
  4856. value = value.substring(1, value.length - 1);
  4857. }
  4858. else if (
  4859. (firstChar == "'" || firstChar == "‘" || firstChar == "’")
  4860. &&
  4861. (lastChar == "'" || lastChar == "‘" || lastChar == "’")
  4862. ) {
  4863. value = value.substring(1, value.length - 1);
  4864. }
  4865. }
  4866. if (section) {
  4867. attr = attr.replace(REGEXP_DESPACE, REGEXP_DESPACE_REPLACE).toLowerCase();
  4868. attr = attr.replace(REGEXP_ALPHA_ONLY, REGEXP_ALPHA_ONLY_REPLACE);
  4869. if (attr) {
  4870. let attrSuffix = "";
  4871. let attrCounter = 1;
  4872. if (attr in attrCounters) {
  4873. attrCounter = attrCounters[attr];
  4874. attrCounter++;
  4875. attrSuffix = "_" + attrCounter;
  4876. }
  4877. attrCounters[attr] = attrCounter;
  4878. attr += attrSuffix;
  4879. section[attr] = value;
  4880. }
  4881. }
  4882. state = STATE_IDLE;
  4883. }
  4884. break;
  4885. }
  4886. }
  4887. }
  4888. catch (err) {
  4889. crdtuxp.logError(arguments, "throws " + err);
  4890. }
  4891. }
  4892. while (false);
  4893. return retVal;
  4894. }
  4895. module.exports.readINI = readINI;
  4896. /**
  4897. * Calculate the relative path to go from a root path to a target path
  4898. *
  4899. * @function relativeTo
  4900. * @memberof crdtuxp.path
  4901. *
  4902. * @param {string} rootPath - the base path to relate to
  4903. * @param {string} targetPath - the base path to reach from the root path
  4904. * @param {string=} pathSeparator - optional: the separator to use. Defaults to the system separator
  4905. * @returns {string|undefined} relative path
  4906. */
  4907. function relativeTo(rootPath, targetPath, pathSeparator) {
  4908. // coderstate: function
  4909. let retVal = undefined;
  4910. do {
  4911. try {
  4912. if (! pathSeparator) {
  4913. pathSeparator = module.exports.path.SEPARATOR
  4914. }
  4915. let splitRootPath = rootPath.split(pathSeparator);
  4916. let splitTargetPath = targetPath.split(pathSeparator);
  4917. let relativePath = "";
  4918. let rootIdx = 0;
  4919. let targetIdx = 0;
  4920. while (rootIdx < splitRootPath.length || targetIdx < splitTargetPath.length) {
  4921. // Skip empty segments
  4922. let rootSegment = undefined;
  4923. while (! rootSegment && rootIdx < splitRootPath.length) {
  4924. rootSegment = splitRootPath[rootIdx];
  4925. rootIdx++;
  4926. }
  4927. let targetSegment = undefined;
  4928. while (! targetSegment && targetIdx < splitTargetPath.length) {
  4929. targetSegment = splitTargetPath[targetIdx];
  4930. targetIdx++;
  4931. }
  4932. if (rootSegment && targetSegment) {
  4933. if (rootSegment != targetSegment) {
  4934. if (! relativePath) {
  4935. relativePath = ".." + pathSeparator + targetSegment;
  4936. }
  4937. else {
  4938. relativePath = ".." + pathSeparator + relativePath + pathSeparator + targetSegment;
  4939. }
  4940. }
  4941. }
  4942. else if (rootSegment) {
  4943. relativePath = ".." + pathSeparator + relativePath;
  4944. }
  4945. else if (targetSegment) {
  4946. relativePath = relativePath + pathSeparator + targetSegment;
  4947. }
  4948. }
  4949. retVal = relativePath;
  4950. }
  4951. catch (err) {
  4952. crdtuxp.logError(arguments, "throws " + err);
  4953. }
  4954. }
  4955. while (false);
  4956. return retVal;
  4957. }
  4958. module.exports.path.relativeTo = relativeTo;
  4959. /**
  4960. * Extend or shorten a string to an exact length, adding <code>padChar</code> as needed
  4961. *
  4962. * @function rightPad
  4963. * @memberof crdtuxp
  4964. *
  4965. * @param {string} s - string to be extended or shortened
  4966. * @param {string} padChar - string to append repeatedly if length needs to extended
  4967. * @param {number} len - desired result length
  4968. * @returns {string} padded or shortened string
  4969. */
  4970. function rightPad(s, padChar, len) {
  4971. // coderstate: function
  4972. let retVal = "";
  4973. do {
  4974. try {
  4975. retVal = s + "";
  4976. if (retVal.length == len) {
  4977. break;
  4978. }
  4979. if (retVal.length > len) {
  4980. retVal = retVal.substring(0, len);
  4981. break;
  4982. }
  4983. const padLength = len - retVal.length;
  4984. const padding = new Array(padLength + 1).join(padChar)
  4985. retVal = retVal + padding;
  4986. }
  4987. catch (err) {
  4988. crdtuxp.logError(arguments, "throws " + err);
  4989. }
  4990. }
  4991. while (false);
  4992. return retVal;
  4993. }
  4994. module.exports.rightPad = rightPad;
  4995. /**
  4996. * Fetch a localized string.
  4997. *
  4998. * @function S
  4999. * @memberof crdtuxp
  5000. *
  5001. * @param {string} stringCode - a token for the string to be localized (e.g. BTN_OK)
  5002. * @param {string=} locale - a locale. Optional - defaults to "en_US"
  5003. * @returns {string} a localized string. If the stringCode is not found, returns the stringCode itself.
  5004. */
  5005. function S(stringCode, locale) {
  5006. // coderstate: function
  5007. let retVal = stringCode;
  5008. do {
  5009. try {
  5010. if (! locale) {
  5011. locale = DEFAULT_LOCALE;
  5012. }
  5013. if (! (stringCode in LOCALE_STRINGS)) {
  5014. break;
  5015. }
  5016. const localeStrings = LOCALE_STRINGS[stringCode];
  5017. if (locale in localeStrings) {
  5018. retVal = localeStrings[locale];
  5019. }
  5020. else if (LOCALE_EN_US in localeStrings) {
  5021. retVal = localeStrings[LOCALE_EN_US];
  5022. }
  5023. }
  5024. catch (err) {
  5025. crdtuxp.logError(arguments, "throws " + err);
  5026. }
  5027. }
  5028. while (false);
  5029. return retVal;
  5030. }
  5031. module.exports.S = S;
  5032. /**
  5033. * Send in activation data so the daemon can determine whether some software is currently activated or not.<br>
  5034. * <br>
  5035. * Needs to be followed by a <code>crdtuxp.sublicense()</code> call
  5036. *
  5037. * @function setIssuer
  5038. * @memberof crdtuxp
  5039. *
  5040. * @param {string} issuerGUID - a GUID identifier for the developer account as seen in the PluginInstaller
  5041. * @param {string} issuerEmail - the email for the developer account as seen in the PluginInstaller
  5042. * @returns {Promise<boolean|undefined>} - success or failure
  5043. */
  5044. function setIssuer(issuerGUID, issuerEmail) {
  5045. // coderstate: promisor
  5046. let retVal = RESOLVED_PROMISE_UNDEFINED;
  5047. do {
  5048. try {
  5049. const responsePromise =
  5050. evalTQL(
  5051. "setIssuer(" + dQ(issuerGUID) + "," + dQ(issuerEmail) + ") ? \"true\" : \"false\""
  5052. );
  5053. if (! responsePromise) {
  5054. break;
  5055. }
  5056. function evalTQLResolveFtn(response) {
  5057. // codestate: resolver
  5058. let retVal;
  5059. do {
  5060. if (! response || response.error) {
  5061. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  5062. break;
  5063. }
  5064. retVal = response.text == "true";
  5065. }
  5066. while (false);
  5067. return retVal;
  5068. };
  5069. function evalTQLRejectFtn(reason) {
  5070. // coderstate: rejector
  5071. crdtuxp.logError(arguments, "rejected for " + reason);
  5072. return undefined;
  5073. };
  5074. retVal = responsePromise.then(
  5075. evalTQLResolveFtn,
  5076. evalTQLRejectFtn
  5077. );
  5078. }
  5079. catch (err) {
  5080. crdtuxp.logError(arguments, "throws " + err);
  5081. }
  5082. }
  5083. while (false);
  5084. return retVal;
  5085. }
  5086. module.exports.setIssuer = setIssuer;
  5087. /**
  5088. * Wrap a string or a byte array into single quotes, encoding any binary data as a string.<br>
  5089. * Knows how to handle Unicode characters or binary zeroes.<br>
  5090. * <br>
  5091. * When the input is a string, high Unicode characters are encoded as <code>\uHHHH</code><br>
  5092. * <br>
  5093. * When the input is a byte array, all bytes are encoded as <code>\xHH</code> escape sequences.<br>
  5094. *
  5095. * @function sQ
  5096. * @memberof crdtuxp
  5097. *
  5098. * @param {string} s_or_ByteArr - a Unicode string or an array of bytes
  5099. * @returns {string} a string enclosed in double quotes. This string is pure 7-bit ASCII and can<br>
  5100. * be used into generated script code<br>
  5101. * Example:<br>
  5102. * <code>let script = "a=b(" + crdtuxp.sQ(somedata) + ");";</code>
  5103. */
  5104. function sQ(s_or_ByteArr) {
  5105. // coderstate: function
  5106. let retVal;
  5107. try {
  5108. retVal = enQuote__(s_or_ByteArr, "'");
  5109. }
  5110. catch (err) {
  5111. crdtuxp.logError(arguments, "throws " + err);
  5112. }
  5113. return retVal;
  5114. }
  5115. module.exports.sQ = sQ;
  5116. /**
  5117. * Store some persistent data (e.g. a time stamp to determine a demo version lapsing)<br>
  5118. * <br>
  5119. * Only available to paid developer accounts
  5120. *
  5121. * @function setPersistData
  5122. * @memberof crdtuxp
  5123. *
  5124. * @param {string} issuer - a GUID identifier for the developer account as seen in the PluginInstaller
  5125. * @param {string} attribute - an attribute name for the data
  5126. * @param {string} password - the password (created by the developer) needed to decode the persistent data
  5127. * @param {string} data - any data to persist
  5128. * @returns {Promise<boolean|undefined>} success or failure
  5129. */
  5130. function setPersistData(issuer, attribute, password, data) {
  5131. // coderstate: promisor
  5132. let retVal = RESOLVED_PROMISE_UNDEFINED;
  5133. do {
  5134. try {
  5135. const responsePromise =
  5136. evalTQL(
  5137. "setPersistData(" +
  5138. dQ(issuer) + "," +
  5139. dQ(attribute) + "," +
  5140. dQ(password) + "," +
  5141. dQ(data) +
  5142. ") ? \"true\" : \"false\""
  5143. );
  5144. if (! responsePromise) {
  5145. break;
  5146. }
  5147. function evalTQLResolveFtn(response) {
  5148. // codestate: resolver
  5149. let retVal;
  5150. do {
  5151. if (! response || response.error) {
  5152. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  5153. break;
  5154. }
  5155. retVal = response.text == "true";
  5156. }
  5157. while (false);
  5158. return retVal;
  5159. };
  5160. function evalTQLRejectFtn(reason) {
  5161. // coderstate: rejector
  5162. crdtuxp.logError(arguments, "rejected for " + reason);
  5163. return undefined;
  5164. };
  5165. retVal = responsePromise.then(
  5166. evalTQLResolveFtn,
  5167. evalTQLRejectFtn
  5168. );
  5169. }
  5170. catch (err) {
  5171. crdtuxp.logError(arguments, "throws " + err);
  5172. }
  5173. }
  5174. while (false);
  5175. return retVal;
  5176. }
  5177. module.exports.setPersistData = setPersistData;
  5178. /**
  5179. * Remove a trailing separator, if any, from a path
  5180. *
  5181. * @function stripTrailingSeparator
  5182. * @memberof crdtuxp
  5183. *
  5184. * @param {string} filePath - a file path
  5185. * @param {string=} separator - the separator to use. If omitted, will try to guess the separator.
  5186. * @returns the file path without trailing separator
  5187. */
  5188. function stripTrailingSeparator(filePath, separator) {
  5189. // coderstate: function
  5190. let retVal = filePath;
  5191. do {
  5192. try {
  5193. if (! filePath) {
  5194. break;
  5195. }
  5196. const lastChar = filePath.substr(-1);
  5197. if (! separator) {
  5198. if (lastChar == crdtuxp.path.SEPARATOR || lastChar == crdtuxp.path.OTHER_PLATFORM_SEPARATOR) {
  5199. retVal = filePath.substr(0, filePath.length - 1);
  5200. }
  5201. }
  5202. else {
  5203. if (lastChar == separator) {
  5204. retVal = filePath.substr(0, filePath.length - 1);
  5205. }
  5206. }
  5207. }
  5208. catch (err) {
  5209. crdtuxp.logError(arguments, "throws " + err);
  5210. }
  5211. }
  5212. while (false);
  5213. return retVal;
  5214. }
  5215. module.exports.stripTrailingSeparator = stripTrailingSeparator;
  5216. /**
  5217. * Encode a string into an byte array using UTF-8
  5218. *
  5219. * @function strToUTF8
  5220. * @memberof crdtuxp
  5221. *
  5222. * @param {string} in_s - a string
  5223. * @returns {array|undefined} a byte array
  5224. */
  5225. function strToUTF8(in_s) {
  5226. // coderstate: function
  5227. let retVal = undefined;
  5228. try {
  5229. let idx = 0;
  5230. let len = in_s.length;
  5231. let cCode;
  5232. while (idx < len) {
  5233. cCode = in_s.charCodeAt(idx);
  5234. idx++;
  5235. let bytes = charCodeToUTF8__(cCode);
  5236. if (! bytes) {
  5237. retVal = undefined;
  5238. break;
  5239. }
  5240. else {
  5241. for (let byteIdx = 0; byteIdx < bytes.length; byteIdx++) {
  5242. if (! retVal) {
  5243. retVal = [];
  5244. }
  5245. retVal.push(bytes[byteIdx]);
  5246. }
  5247. }
  5248. }
  5249. }
  5250. catch (err) {
  5251. crdtuxp.logError(arguments, "throws " + err);
  5252. }
  5253. return retVal;
  5254. }
  5255. module.exports.strToUTF8 = strToUTF8;
  5256. /**
  5257. * Send in sublicense info generated in the PluginInstaller so the daemon can determine whether some<br>
  5258. * software is currently activated or not.<br>
  5259. * <br>
  5260. * Needs to be preceded by a <code>crdtuxp.setIssuer()</code> call.
  5261. *
  5262. * @function sublicense
  5263. * @memberof crdtuxp
  5264. *
  5265. * @param {string} key - key needed to decode activation data
  5266. * @param {string} activation - encrypted activation data
  5267. * @returns { Promise<boolean|undefined> } success or failure
  5268. */
  5269. function sublicense(key, activation) {
  5270. // coderstate: promisor
  5271. let retVal = RESOLVED_PROMISE_UNDEFINED;
  5272. do {
  5273. try {
  5274. const responsePromise =
  5275. evalTQL(
  5276. "sublicense(" + dQ(key) + "," + dQ(activation) + ") ? \"true\" : \"false\""
  5277. );
  5278. if (! responsePromise) {
  5279. break;
  5280. }
  5281. function evalTQLResolveFtn(response) {
  5282. // codestate: resolver
  5283. let retVal;
  5284. do {
  5285. if (! response || response.error) {
  5286. crdtuxp.logError(arguments, "bad response, error = " + response?.error);
  5287. break;
  5288. }
  5289. retVal = response.text == "true";
  5290. }
  5291. while (false);
  5292. return retVal;
  5293. };
  5294. function evalTQLRejectFtn(reason) {
  5295. // coderstate: rejector
  5296. crdtuxp.logError(arguments, "rejected for " + reason);
  5297. return undefined;
  5298. };
  5299. retVal = responsePromise.then(
  5300. evalTQLResolveFtn,
  5301. evalTQLRejectFtn
  5302. );
  5303. }
  5304. catch (err) {
  5305. crdtuxp.logError(arguments, "throws " + err);
  5306. }
  5307. }
  5308. while (false);
  5309. return retVal;
  5310. }
  5311. module.exports.sublicense = sublicense;
  5312. /**
  5313. * Test if we can access the path-based file I/O APIs
  5314. *
  5315. * @function testDirectFileAccess
  5316. * @memberof crdtuxp
  5317. *
  5318. * @returns {boolean} whether APIs are accessible
  5319. */
  5320. function testDirectFileAccess() {
  5321. // coderstate: function
  5322. let retVal = false;
  5323. do {
  5324. try {
  5325. let uxpContext = crdtuxp.getUXPContext();
  5326. if (! uxpContext) {
  5327. crdtuxp.logError(arguments, "failed to get uxpContext");
  5328. break;
  5329. }
  5330. let homeDir = uxpContext.os.homedir();
  5331. if (! homeDir) {
  5332. crdtuxp.logError(arguments, "failed to os.homedir()");
  5333. break;
  5334. }
  5335. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  5336. const stats = uxpContext.fs.lstatSync(homeDir);
  5337. if (stats && stats.isDirectory()) {
  5338. retVal = true;
  5339. }
  5340. }
  5341. catch (err) {
  5342. }
  5343. }
  5344. while (false);
  5345. return retVal;
  5346. }
  5347. module.exports.testDirectFileAccess = testDirectFileAccess;
  5348. /**
  5349. * Test if we can access the network APIs
  5350. *
  5351. * @function testNetworkAccess
  5352. * @memberof crdtuxp
  5353. *
  5354. * @returns {Promise<boolean|undefined>} whether APIs are accessible
  5355. */
  5356. function testNetworkAccess() {
  5357. // coderstate: promisor
  5358. let retVal = RESOLVED_PROMISE_FALSE;
  5359. try {
  5360. let context = crdtuxp.getContext();
  5361. let savedForceUseDaemon = context.IS_FORCE_USE_DAEMON;
  5362. let savedForceDaemonFileBasedAPI = context.IS_FORCE_DAEMON_FILE_BASED_API;
  5363. let uxpContext = crdtuxp.getUXPContext();
  5364. let savedHasNetworkAccess = uxpContext.hasNetworkAccess;
  5365. context.IS_FORCE_USE_DAEMON = true;
  5366. context.IS_FORCE_DAEMON_FILE_BASED_API = false;
  5367. uxpContext.hasNetworkAccess = true;
  5368. try {
  5369. return crdtuxp.base64encode("abc").then(
  5370. function blowPipesResolveFtn(result) {
  5371. return result == "YWJj";
  5372. }
  5373. ).catch(
  5374. function blowPipesRejectFtn(reason) {
  5375. return false;
  5376. }
  5377. );
  5378. }
  5379. catch (err) {
  5380. crdtuxp.logError(arguments, "throws " + err);
  5381. }
  5382. uxpContext.hasNetworkAccess = savedHasNetworkAccess;
  5383. context.IS_FORCE_USE_DAEMON = savedForceUseDaemon;
  5384. context.IS_FORCE_DAEMON_FILE_BASED_API = savedForceDaemonFileBasedAPI;
  5385. }
  5386. catch (err) {
  5387. crdtuxp.logError(arguments, "throws " + err);
  5388. }
  5389. return retVal;
  5390. }
  5391. module.exports.testNetworkAccess = testNetworkAccess;
  5392. /**
  5393. * Convert an integer into a hex representation with a fixed number of digits.<br>
  5394. * Negative numbers are converted using 2-s complement (so <code>-15</code> results in <code>0x01</code>)
  5395. *
  5396. * @function toHex
  5397. * @memberof crdtuxp
  5398. *
  5399. * @param {number} i - integer to convert to hex
  5400. * @param {number} numDigits - How many digits. Defaults to 4 if omitted.
  5401. * @returns { string } hex-encoded integer
  5402. */
  5403. let TO_HEX_BUNCH_OF_ZEROES = "";
  5404. function toHex(i, numDigits) {
  5405. // coderstate: function
  5406. let retVal = "";
  5407. do {
  5408. try {
  5409. if (! numDigits) {
  5410. numDigits = 4;
  5411. }
  5412. if (i < 0) {
  5413. let upper = intPow(2, numDigits*4);
  5414. if (! upper) {
  5415. break;
  5416. }
  5417. // Calculate 2's complement with numDigits if negative
  5418. i = (upper + i) & (upper - 1);
  5419. }
  5420. // Calculate and cache a long enough string of zeroes
  5421. let zeroes = TO_HEX_BUNCH_OF_ZEROES;
  5422. if (! zeroes) {
  5423. zeroes = "0";
  5424. }
  5425. if (zeroes.length < numDigits) {
  5426. while (zeroes.length < numDigits) {
  5427. zeroes += zeroes;
  5428. }
  5429. TO_HEX_BUNCH_OF_ZEROES = zeroes;
  5430. }
  5431. retVal = i.toString(16).toLowerCase(); // Probably always lowercase by default, but just in case...
  5432. if (retVal.length > numDigits) {
  5433. retVal = retVal.substring(retVal.length - numDigits);
  5434. }
  5435. else if (retVal.length < numDigits) {
  5436. retVal = zeroes.substring(0, numDigits - retVal.length) + retVal;
  5437. }
  5438. }
  5439. catch (err) {
  5440. crdtuxp.logError(arguments, "throws " + err);
  5441. }
  5442. }
  5443. while (false);
  5444. return retVal;
  5445. }
  5446. module.exports.toHex = toHex;
  5447. /**
  5448. * Conversion factor from a length unit into inches
  5449. *
  5450. * @function unitToInchFactor
  5451. * @memberof crdtuxp
  5452. *
  5453. * @param {string} in_unit - unit name (<code>crdtuxp.UNIT_NAME...</code>)
  5454. * @returns {number} conversion factor or 1.0 if unknown/not applicable
  5455. */
  5456. function unitToInchFactor(in_unit) {
  5457. // coderstate: function
  5458. let retVal = 1.0;
  5459. try {
  5460. switch (in_unit) {
  5461. case crdtuxp.UNIT_NAME_CM:
  5462. retVal = 1.0/2.54;
  5463. break;
  5464. case crdtuxp.UNIT_NAME_MM:
  5465. retVal = 1.0/25.4;
  5466. break;
  5467. case crdtuxp.UNIT_NAME_CICERO:
  5468. retVal = 0.17762;
  5469. break;
  5470. case crdtuxp.UNIT_NAME_PICA:
  5471. retVal = 1.0/12.0;
  5472. break;
  5473. case crdtuxp.UNIT_NAME_PIXEL:
  5474. retVal = 1.0/72.0;
  5475. break;
  5476. case crdtuxp.UNIT_NAME_POINT:
  5477. retVal = 1.0/72.0;
  5478. break;
  5479. }
  5480. }
  5481. catch (err) {
  5482. crdtuxp.logError(arguments, "throws " + err);
  5483. }
  5484. return retVal;
  5485. }
  5486. module.exports.unitToInchFactor = unitToInchFactor;
  5487. /**
  5488. * Wait for a file to appear. Only works in UXP contexts with direct file access
  5489. *
  5490. * @function waitForFile
  5491. * @memberof crdtuxp
  5492. *
  5493. * @param {string} filePath - file that needs to appear
  5494. * @param {number=} interval - how often to check for file (milliseconds)
  5495. * @param {number=} timeout - how long to wait for file (milliseconds)
  5496. * @returns {Promise<boolean|undefined>} whether file appeared or not
  5497. */
  5498. function waitForFile(
  5499. filePath,
  5500. interval = DEFAULT_WAIT_FILE_INTERVAL_MILLISECONDS,
  5501. timeout = DEFAULT_WAIT_FILE_TIMEOUT_MILLISECONDS) {
  5502. // coderstate: promisor
  5503. let retVal = RESOLVED_PROMISE_UNDEFINED;
  5504. do {
  5505. try {
  5506. var uxpContext = getUXPContext();
  5507. if (! uxpContext.hasDirectFileAccess) {
  5508. crdtuxp.logError(arguments, "need direct file access");
  5509. break;
  5510. }
  5511. let endTime = (new Date()).getTime() + timeout;
  5512. function checkFile() {
  5513. // coderstate: promisor
  5514. function checkFileExecutor(resolveFtn, rejectFtn) {
  5515. // coderstate: executor
  5516. const now = Date.now();
  5517. if (endTime < now) {
  5518. crdtuxp.logNote(arguments, "already timed out");
  5519. resolveFtn(undefined);
  5520. } else {
  5521. try {
  5522. // https://developer.adobe.com/photoshop/uxp/2022/uxp-api/reference-js/Modules/fs/
  5523. const stats = uxpContext.fs.lstatSync(filePath);
  5524. if (stats) {
  5525. crdtuxp.logTrace(arguments, "file appeared");
  5526. resolveFtn(true);
  5527. } else {
  5528. crdtuxp.logNote(arguments, "no stats returned");
  5529. delayFunction(interval, checkFile).
  5530. then(
  5531. resolveFtn,
  5532. rejectFtn
  5533. );
  5534. }
  5535. }
  5536. catch (err) {
  5537. if (err != FILE_NOT_EXIST_ERROR) {
  5538. crdtuxp.logNote(arguments, "throws " + err);
  5539. }
  5540. else {
  5541. crdtuxp.logTrace(arguments, "file not present yet");
  5542. }
  5543. delayFunction(interval, checkFile).
  5544. then(
  5545. resolveFtn,
  5546. rejectFtn
  5547. );
  5548. }
  5549. }
  5550. };
  5551. return new Promise(checkFileExecutor);
  5552. };
  5553. retVal = checkFile();
  5554. }
  5555. catch (err) {
  5556. crdtuxp.logError(arguments, "throws " + err);
  5557. }
  5558. }
  5559. while (false);
  5560. return retVal;
  5561. }
  5562. module.exports.waitForFile = waitForFile;