@jackctaylor/roblox-ts 3.0.0-projectrefs.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (450) hide show
  1. package/CHANGELOG.md +716 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -0
  4. package/include/Promise.lua +2068 -0
  5. package/include/RuntimeLib.lua +258 -0
  6. package/out/CLI/cli.d.ts +2 -0
  7. package/out/CLI/cli.js +41 -0
  8. package/out/CLI/commands/build.d.ts +7 -0
  9. package/out/CLI/commands/build.js +438 -0
  10. package/out/CLI/errors/CLIError.d.ts +4 -0
  11. package/out/CLI/errors/CLIError.js +12 -0
  12. package/out/CLI/index.d.ts +3 -0
  13. package/out/CLI/index.js +22 -0
  14. package/out/CLI/test.d.ts +1 -0
  15. package/out/CLI/test.js +82 -0
  16. package/out/CLI/util/patchFs.d.ts +1 -0
  17. package/out/CLI/util/patchFs.js +26 -0
  18. package/out/Project/classes/VirtualFileSystem.d.ts +14 -0
  19. package/out/Project/classes/VirtualFileSystem.js +102 -0
  20. package/out/Project/classes/VirtualProject.d.ts +15 -0
  21. package/out/Project/classes/VirtualProject.js +121 -0
  22. package/out/Project/functions/buildProject.d.ts +18 -0
  23. package/out/Project/functions/buildProject.js +48 -0
  24. package/out/Project/functions/buildProjectReferences.d.ts +3 -0
  25. package/out/Project/functions/buildProjectReferences.js +78 -0
  26. package/out/Project/functions/buildSolution.d.ts +10 -0
  27. package/out/Project/functions/buildSolution.js +97 -0
  28. package/out/Project/functions/checkFileName.d.ts +1 -0
  29. package/out/Project/functions/checkFileName.js +18 -0
  30. package/out/Project/functions/checkRojoConfig.d.ts +4 -0
  31. package/out/Project/functions/checkRojoConfig.js +26 -0
  32. package/out/Project/functions/cleanup.d.ts +2 -0
  33. package/out/Project/functions/cleanup.js +30 -0
  34. package/out/Project/functions/compileFiles.d.ts +4 -0
  35. package/out/Project/functions/compileFiles.js +160 -0
  36. package/out/Project/functions/compileProject.d.ts +14 -0
  37. package/out/Project/functions/compileProject.js +71 -0
  38. package/out/Project/functions/copyFiles.d.ts +3 -0
  39. package/out/Project/functions/copyFiles.js +13 -0
  40. package/out/Project/functions/copyInclude.d.ts +2 -0
  41. package/out/Project/functions/copyInclude.js +17 -0
  42. package/out/Project/functions/copyItem.d.ts +3 -0
  43. package/out/Project/functions/copyItem.js +27 -0
  44. package/out/Project/functions/createNodeModulesPathMapping.d.ts +1 -0
  45. package/out/Project/functions/createNodeModulesPathMapping.js +31 -0
  46. package/out/Project/functions/createPathTranslator.d.ts +4 -0
  47. package/out/Project/functions/createPathTranslator.js +22 -0
  48. package/out/Project/functions/createProgramFactory.d.ts +3 -0
  49. package/out/Project/functions/createProgramFactory.js +31 -0
  50. package/out/Project/functions/createProjectData.d.ts +2 -0
  51. package/out/Project/functions/createProjectData.js +102 -0
  52. package/out/Project/functions/createProjectProgram.d.ts +3 -0
  53. package/out/Project/functions/createProjectProgram.js +11 -0
  54. package/out/Project/functions/getChangedFilePaths.d.ts +2 -0
  55. package/out/Project/functions/getChangedFilePaths.js +47 -0
  56. package/out/Project/functions/getChangedSourceFiles.d.ts +2 -0
  57. package/out/Project/functions/getChangedSourceFiles.js +19 -0
  58. package/out/Project/functions/getParsedCommandLine.d.ts +3 -0
  59. package/out/Project/functions/getParsedCommandLine.js +41 -0
  60. package/out/Project/functions/getProjectReferences.d.ts +2 -0
  61. package/out/Project/functions/getProjectReferences.js +65 -0
  62. package/out/Project/functions/getResolvedProjectReferences.d.ts +3 -0
  63. package/out/Project/functions/getResolvedProjectReferences.js +43 -0
  64. package/out/Project/functions/setupProjectWatchProgram.d.ts +2 -0
  65. package/out/Project/functions/setupProjectWatchProgram.js +352 -0
  66. package/out/Project/functions/setupSolutionWatchProgram.d.ts +2 -0
  67. package/out/Project/functions/setupSolutionWatchProgram.js +355 -0
  68. package/out/Project/functions/tryRemoveOutput.d.ts +2 -0
  69. package/out/Project/functions/tryRemoveOutput.js +30 -0
  70. package/out/Project/functions/validateCompilerOptions.d.ts +2 -0
  71. package/out/Project/functions/validateCompilerOptions.js +87 -0
  72. package/out/Project/index.d.ts +4 -0
  73. package/out/Project/index.js +20 -0
  74. package/out/Project/preEmitDiagnostics/fileUsesCommentDirectives.d.ts +3 -0
  75. package/out/Project/preEmitDiagnostics/fileUsesCommentDirectives.js +28 -0
  76. package/out/Project/transformers/builtin/transformPaths.d.ts +5 -0
  77. package/out/Project/transformers/builtin/transformPaths.js +129 -0
  78. package/out/Project/transformers/builtin/transformTypeReferenceDirectives.d.ts +2 -0
  79. package/out/Project/transformers/builtin/transformTypeReferenceDirectives.js +23 -0
  80. package/out/Project/transformers/createTransformerList.d.ts +4 -0
  81. package/out/Project/transformers/createTransformerList.js +87 -0
  82. package/out/Project/transformers/createTransformerWatcher.d.ts +3 -0
  83. package/out/Project/transformers/createTransformerWatcher.js +59 -0
  84. package/out/Project/transformers/getPluginConfigs.d.ts +2 -0
  85. package/out/Project/transformers/getPluginConfigs.js +34 -0
  86. package/out/Project/util/createReadBuildProgramHost.d.ts +5 -0
  87. package/out/Project/util/createReadBuildProgramHost.js +15 -0
  88. package/out/Project/util/getCustomPreEmitDiagnostics.d.ts +4 -0
  89. package/out/Project/util/getCustomPreEmitDiagnostics.js +13 -0
  90. package/out/Project/util/isCompilableFile.d.ts +1 -0
  91. package/out/Project/util/isCompilableFile.js +18 -0
  92. package/out/Project/util/walkDirectorySync.d.ts +1 -0
  93. package/out/Project/util/walkDirectorySync.js +22 -0
  94. package/out/Shared/classes/Lazy.d.ts +8 -0
  95. package/out/Shared/classes/Lazy.js +22 -0
  96. package/out/Shared/classes/LogService.d.ts +9 -0
  97. package/out/Shared/classes/LogService.js +37 -0
  98. package/out/Shared/constants.d.ts +23 -0
  99. package/out/Shared/constants.js +50 -0
  100. package/out/Shared/diagnostics.d.ts +79 -0
  101. package/out/Shared/diagnostics.js +140 -0
  102. package/out/Shared/errors/DiagnosticError.d.ts +7 -0
  103. package/out/Shared/errors/DiagnosticError.js +16 -0
  104. package/out/Shared/errors/LoggableError.d.ts +5 -0
  105. package/out/Shared/errors/LoggableError.js +14 -0
  106. package/out/Shared/errors/ProjectError.d.ts +4 -0
  107. package/out/Shared/errors/ProjectError.js +12 -0
  108. package/out/Shared/index.d.ts +0 -0
  109. package/out/Shared/index.js +2 -0
  110. package/out/Shared/types.d.ts +50 -0
  111. package/out/Shared/types.js +3 -0
  112. package/out/Shared/util/assert.d.ts +1 -0
  113. package/out/Shared/util/assert.js +12 -0
  114. package/out/Shared/util/benchmark.d.ts +3 -0
  115. package/out/Shared/util/benchmark.js +32 -0
  116. package/out/Shared/util/createDiagnosticWithLocation.d.ts +3 -0
  117. package/out/Shared/util/createDiagnosticWithLocation.js +29 -0
  118. package/out/Shared/util/createGithubLink.d.ts +1 -0
  119. package/out/Shared/util/createGithubLink.js +12 -0
  120. package/out/Shared/util/createTextDiagnostic.d.ts +2 -0
  121. package/out/Shared/util/createTextDiagnostic.js +18 -0
  122. package/out/Shared/util/findAncestorDir.d.ts +1 -0
  123. package/out/Shared/util/findAncestorDir.js +16 -0
  124. package/out/Shared/util/findLastIndex.d.ts +1 -0
  125. package/out/Shared/util/findLastIndex.js +12 -0
  126. package/out/Shared/util/formatDiagnostics.d.ts +2 -0
  127. package/out/Shared/util/formatDiagnostics.js +19 -0
  128. package/out/Shared/util/getCanonicalFileName.d.ts +2 -0
  129. package/out/Shared/util/getCanonicalFileName.js +10 -0
  130. package/out/Shared/util/getOrSetDefault.d.ts +1 -0
  131. package/out/Shared/util/getOrSetDefault.js +12 -0
  132. package/out/Shared/util/getRootDirs.d.ts +2 -0
  133. package/out/Shared/util/getRootDirs.js +10 -0
  134. package/out/Shared/util/hasErrors.d.ts +2 -0
  135. package/out/Shared/util/hasErrors.js +11 -0
  136. package/out/Shared/util/isPathDescendantOf.d.ts +1 -0
  137. package/out/Shared/util/isPathDescendantOf.js +11 -0
  138. package/out/Shared/util/realPathExistsSync.d.ts +1 -0
  139. package/out/Shared/util/realPathExistsSync.js +13 -0
  140. package/out/Shared/warn.d.ts +1 -0
  141. package/out/Shared/warn.js +12 -0
  142. package/out/TSTransformer/classes/DiagnosticService.d.ts +11 -0
  143. package/out/TSTransformer/classes/DiagnosticService.js +37 -0
  144. package/out/TSTransformer/classes/MacroManager.d.ts +46 -0
  145. package/out/TSTransformer/classes/MacroManager.js +178 -0
  146. package/out/TSTransformer/classes/MultiTransformState.d.ts +9 -0
  147. package/out/TSTransformer/classes/MultiTransformState.js +15 -0
  148. package/out/TSTransformer/classes/TransformState.d.ts +73 -0
  149. package/out/TSTransformer/classes/TransformState.js +307 -0
  150. package/out/TSTransformer/index.d.ts +4 -0
  151. package/out/TSTransformer/index.js +23 -0
  152. package/out/TSTransformer/macros/callMacros.d.ts +2 -0
  153. package/out/TSTransformer/macros/callMacros.js +56 -0
  154. package/out/TSTransformer/macros/constructorMacros.d.ts +2 -0
  155. package/out/TSTransformer/macros/constructorMacros.js +97 -0
  156. package/out/TSTransformer/macros/identifierMacros.d.ts +2 -0
  157. package/out/TSTransformer/macros/identifierMacros.js +7 -0
  158. package/out/TSTransformer/macros/propertyCallMacros.d.ts +4 -0
  159. package/out/TSTransformer/macros/propertyCallMacros.js +726 -0
  160. package/out/TSTransformer/macros/types.d.ts +12 -0
  161. package/out/TSTransformer/macros/types.js +3 -0
  162. package/out/TSTransformer/nodes/binding/transformArrayAssignmentPattern.d.ts +4 -0
  163. package/out/TSTransformer/nodes/binding/transformArrayAssignmentPattern.js +78 -0
  164. package/out/TSTransformer/nodes/binding/transformArrayBindingPattern.d.ts +4 -0
  165. package/out/TSTransformer/nodes/binding/transformArrayBindingPattern.js +52 -0
  166. package/out/TSTransformer/nodes/binding/transformBindingName.d.ts +4 -0
  167. package/out/TSTransformer/nodes/binding/transformBindingName.js +30 -0
  168. package/out/TSTransformer/nodes/binding/transformObjectAssignmentPattern.d.ts +4 -0
  169. package/out/TSTransformer/nodes/binding/transformObjectAssignmentPattern.js +97 -0
  170. package/out/TSTransformer/nodes/binding/transformObjectBindingPattern.d.ts +4 -0
  171. package/out/TSTransformer/nodes/binding/transformObjectBindingPattern.js +57 -0
  172. package/out/TSTransformer/nodes/class/transformClassConstructor.d.ts +7 -0
  173. package/out/TSTransformer/nodes/class/transformClassConstructor.js +96 -0
  174. package/out/TSTransformer/nodes/class/transformClassLikeDeclaration.d.ts +7 -0
  175. package/out/TSTransformer/nodes/class/transformClassLikeDeclaration.js +262 -0
  176. package/out/TSTransformer/nodes/class/transformDecorators.d.ts +4 -0
  177. package/out/TSTransformer/nodes/class/transformDecorators.js +179 -0
  178. package/out/TSTransformer/nodes/class/transformPropertyDeclaration.d.ts +4 -0
  179. package/out/TSTransformer/nodes/class/transformPropertyDeclaration.js +33 -0
  180. package/out/TSTransformer/nodes/expressions/transformArrayLiteralExpression.d.ts +4 -0
  181. package/out/TSTransformer/nodes/expressions/transformArrayLiteralExpression.js +79 -0
  182. package/out/TSTransformer/nodes/expressions/transformAwaitExpression.d.ts +4 -0
  183. package/out/TSTransformer/nodes/expressions/transformAwaitExpression.js +13 -0
  184. package/out/TSTransformer/nodes/expressions/transformBinaryExpression.d.ts +4 -0
  185. package/out/TSTransformer/nodes/expressions/transformBinaryExpression.js +199 -0
  186. package/out/TSTransformer/nodes/expressions/transformBooleanLiteral.d.ts +3 -0
  187. package/out/TSTransformer/nodes/expressions/transformBooleanLiteral.js +15 -0
  188. package/out/TSTransformer/nodes/expressions/transformCallExpression.d.ts +7 -0
  189. package/out/TSTransformer/nodes/expressions/transformCallExpression.js +191 -0
  190. package/out/TSTransformer/nodes/expressions/transformClassExpression.d.ts +3 -0
  191. package/out/TSTransformer/nodes/expressions/transformClassExpression.js +10 -0
  192. package/out/TSTransformer/nodes/expressions/transformConditionalExpression.d.ts +4 -0
  193. package/out/TSTransformer/nodes/expressions/transformConditionalExpression.js +55 -0
  194. package/out/TSTransformer/nodes/expressions/transformDeleteExpression.d.ts +4 -0
  195. package/out/TSTransformer/nodes/expressions/transformDeleteExpression.js +14 -0
  196. package/out/TSTransformer/nodes/expressions/transformElementAccessExpression.d.ts +5 -0
  197. package/out/TSTransformer/nodes/expressions/transformElementAccessExpression.js +62 -0
  198. package/out/TSTransformer/nodes/expressions/transformExpression.d.ts +4 -0
  199. package/out/TSTransformer/nodes/expressions/transformExpression.js +107 -0
  200. package/out/TSTransformer/nodes/expressions/transformFunctionExpression.d.ts +4 -0
  201. package/out/TSTransformer/nodes/expressions/transformFunctionExpression.js +46 -0
  202. package/out/TSTransformer/nodes/expressions/transformIdentifier.d.ts +5 -0
  203. package/out/TSTransformer/nodes/expressions/transformIdentifier.js +147 -0
  204. package/out/TSTransformer/nodes/expressions/transformImportExpression.d.ts +4 -0
  205. package/out/TSTransformer/nodes/expressions/transformImportExpression.js +30 -0
  206. package/out/TSTransformer/nodes/expressions/transformJsxElement.d.ts +3 -0
  207. package/out/TSTransformer/nodes/expressions/transformJsxElement.js +8 -0
  208. package/out/TSTransformer/nodes/expressions/transformJsxExpression.d.ts +4 -0
  209. package/out/TSTransformer/nodes/expressions/transformJsxExpression.js +19 -0
  210. package/out/TSTransformer/nodes/expressions/transformJsxFragment.d.ts +4 -0
  211. package/out/TSTransformer/nodes/expressions/transformJsxFragment.js +28 -0
  212. package/out/TSTransformer/nodes/expressions/transformJsxSelfClosingElement.d.ts +3 -0
  213. package/out/TSTransformer/nodes/expressions/transformJsxSelfClosingElement.js +8 -0
  214. package/out/TSTransformer/nodes/expressions/transformNewExpression.d.ts +4 -0
  215. package/out/TSTransformer/nodes/expressions/transformNewExpression.js +26 -0
  216. package/out/TSTransformer/nodes/expressions/transformNoSubstitutionTemplateLiteral.d.ts +4 -0
  217. package/out/TSTransformer/nodes/expressions/transformNoSubstitutionTemplateLiteral.js +14 -0
  218. package/out/TSTransformer/nodes/expressions/transformNumericLiteral.d.ts +4 -0
  219. package/out/TSTransformer/nodes/expressions/transformNumericLiteral.js +13 -0
  220. package/out/TSTransformer/nodes/expressions/transformObjectLiteralExpression.d.ts +4 -0
  221. package/out/TSTransformer/nodes/expressions/transformObjectLiteralExpression.js +98 -0
  222. package/out/TSTransformer/nodes/expressions/transformOmittedExpression.d.ts +2 -0
  223. package/out/TSTransformer/nodes/expressions/transformOmittedExpression.js +11 -0
  224. package/out/TSTransformer/nodes/expressions/transformParenthesizedExpression.d.ts +4 -0
  225. package/out/TSTransformer/nodes/expressions/transformParenthesizedExpression.js +19 -0
  226. package/out/TSTransformer/nodes/expressions/transformPropertyAccessExpression.d.ts +5 -0
  227. package/out/TSTransformer/nodes/expressions/transformPropertyAccessExpression.js +36 -0
  228. package/out/TSTransformer/nodes/expressions/transformSpreadElement.d.ts +4 -0
  229. package/out/TSTransformer/nodes/expressions/transformSpreadElement.js +35 -0
  230. package/out/TSTransformer/nodes/expressions/transformStringLiteral.d.ts +4 -0
  231. package/out/TSTransformer/nodes/expressions/transformStringLiteral.js +12 -0
  232. package/out/TSTransformer/nodes/expressions/transformSuperKeyword.d.ts +2 -0
  233. package/out/TSTransformer/nodes/expressions/transformSuperKeyword.js +11 -0
  234. package/out/TSTransformer/nodes/expressions/transformTaggedTemplateExpression.d.ts +4 -0
  235. package/out/TSTransformer/nodes/expressions/transformTaggedTemplateExpression.js +27 -0
  236. package/out/TSTransformer/nodes/expressions/transformTemplateExpression.d.ts +4 -0
  237. package/out/TSTransformer/nodes/expressions/transformTemplateExpression.js +25 -0
  238. package/out/TSTransformer/nodes/expressions/transformThisExpression.d.ts +4 -0
  239. package/out/TSTransformer/nodes/expressions/transformThisExpression.js +29 -0
  240. package/out/TSTransformer/nodes/expressions/transformTypeExpression.d.ts +3 -0
  241. package/out/TSTransformer/nodes/expressions/transformTypeExpression.js +8 -0
  242. package/out/TSTransformer/nodes/expressions/transformUnaryExpression.d.ts +5 -0
  243. package/out/TSTransformer/nodes/expressions/transformUnaryExpression.js +68 -0
  244. package/out/TSTransformer/nodes/expressions/transformVoidExpression.d.ts +4 -0
  245. package/out/TSTransformer/nodes/expressions/transformVoidExpression.js +14 -0
  246. package/out/TSTransformer/nodes/expressions/transformYieldExpression.d.ts +4 -0
  247. package/out/TSTransformer/nodes/expressions/transformYieldExpression.js +46 -0
  248. package/out/TSTransformer/nodes/jsx/transformJsx.d.ts +4 -0
  249. package/out/TSTransformer/nodes/jsx/transformJsx.js +36 -0
  250. package/out/TSTransformer/nodes/jsx/transformJsxAttributes.d.ts +4 -0
  251. package/out/TSTransformer/nodes/jsx/transformJsxAttributes.js +83 -0
  252. package/out/TSTransformer/nodes/jsx/transformJsxChildren.d.ts +4 -0
  253. package/out/TSTransformer/nodes/jsx/transformJsxChildren.js +34 -0
  254. package/out/TSTransformer/nodes/jsx/transformJsxTagName.d.ts +4 -0
  255. package/out/TSTransformer/nodes/jsx/transformJsxTagName.js +42 -0
  256. package/out/TSTransformer/nodes/statements/transformBlock.d.ts +4 -0
  257. package/out/TSTransformer/nodes/statements/transformBlock.js +14 -0
  258. package/out/TSTransformer/nodes/statements/transformBreakStatement.d.ts +4 -0
  259. package/out/TSTransformer/nodes/statements/transformBreakStatement.js +24 -0
  260. package/out/TSTransformer/nodes/statements/transformClassDeclaration.d.ts +3 -0
  261. package/out/TSTransformer/nodes/statements/transformClassDeclaration.js +8 -0
  262. package/out/TSTransformer/nodes/statements/transformContinueStatement.d.ts +4 -0
  263. package/out/TSTransformer/nodes/statements/transformContinueStatement.js +24 -0
  264. package/out/TSTransformer/nodes/statements/transformDoStatement.d.ts +4 -0
  265. package/out/TSTransformer/nodes/statements/transformDoStatement.js +31 -0
  266. package/out/TSTransformer/nodes/statements/transformEnumDeclaration.d.ts +4 -0
  267. package/out/TSTransformer/nodes/statements/transformEnumDeclaration.js +97 -0
  268. package/out/TSTransformer/nodes/statements/transformExportAssignment.d.ts +4 -0
  269. package/out/TSTransformer/nodes/statements/transformExportAssignment.js +53 -0
  270. package/out/TSTransformer/nodes/statements/transformExportDeclaration.d.ts +4 -0
  271. package/out/TSTransformer/nodes/statements/transformExportDeclaration.js +109 -0
  272. package/out/TSTransformer/nodes/statements/transformExpressionStatement.d.ts +5 -0
  273. package/out/TSTransformer/nodes/statements/transformExpressionStatement.js +62 -0
  274. package/out/TSTransformer/nodes/statements/transformForOfStatement.d.ts +5 -0
  275. package/out/TSTransformer/nodes/statements/transformForOfStatement.js +375 -0
  276. package/out/TSTransformer/nodes/statements/transformForStatement.d.ts +4 -0
  277. package/out/TSTransformer/nodes/statements/transformForStatement.js +371 -0
  278. package/out/TSTransformer/nodes/statements/transformFunctionDeclaration.d.ts +4 -0
  279. package/out/TSTransformer/nodes/statements/transformFunctionDeclaration.js +68 -0
  280. package/out/TSTransformer/nodes/statements/transformIfStatement.d.ts +5 -0
  281. package/out/TSTransformer/nodes/statements/transformIfStatement.js +46 -0
  282. package/out/TSTransformer/nodes/statements/transformImportDeclaration.d.ts +4 -0
  283. package/out/TSTransformer/nodes/statements/transformImportDeclaration.js +98 -0
  284. package/out/TSTransformer/nodes/statements/transformImportEqualsDeclaration.d.ts +4 -0
  285. package/out/TSTransformer/nodes/statements/transformImportEqualsDeclaration.js +36 -0
  286. package/out/TSTransformer/nodes/statements/transformModuleDeclaration.d.ts +4 -0
  287. package/out/TSTransformer/nodes/statements/transformModuleDeclaration.js +122 -0
  288. package/out/TSTransformer/nodes/statements/transformReturnStatement.d.ts +5 -0
  289. package/out/TSTransformer/nodes/statements/transformReturnStatement.js +74 -0
  290. package/out/TSTransformer/nodes/statements/transformStatement.d.ts +4 -0
  291. package/out/TSTransformer/nodes/statements/transformStatement.js +83 -0
  292. package/out/TSTransformer/nodes/statements/transformSwitchStatement.d.ts +4 -0
  293. package/out/TSTransformer/nodes/statements/transformSwitchStatement.js +105 -0
  294. package/out/TSTransformer/nodes/statements/transformThrowStatement.d.ts +4 -0
  295. package/out/TSTransformer/nodes/statements/transformThrowStatement.js +18 -0
  296. package/out/TSTransformer/nodes/statements/transformTryStatement.d.ts +4 -0
  297. package/out/TSTransformer/nodes/statements/transformTryStatement.js +148 -0
  298. package/out/TSTransformer/nodes/statements/transformVariableStatement.d.ts +8 -0
  299. package/out/TSTransformer/nodes/statements/transformVariableStatement.js +155 -0
  300. package/out/TSTransformer/nodes/statements/transformWhileStatement.d.ts +4 -0
  301. package/out/TSTransformer/nodes/statements/transformWhileStatement.js +30 -0
  302. package/out/TSTransformer/nodes/transformEntityName.d.ts +4 -0
  303. package/out/TSTransformer/nodes/transformEntityName.js +24 -0
  304. package/out/TSTransformer/nodes/transformInitializer.d.ts +4 -0
  305. package/out/TSTransformer/nodes/transformInitializer.js +22 -0
  306. package/out/TSTransformer/nodes/transformInterpolatedStringPart.d.ts +3 -0
  307. package/out/TSTransformer/nodes/transformInterpolatedStringPart.js +12 -0
  308. package/out/TSTransformer/nodes/transformLogical.d.ts +4 -0
  309. package/out/TSTransformer/nodes/transformLogical.js +103 -0
  310. package/out/TSTransformer/nodes/transformLogicalOrCoalescingAssignmentExpression.d.ts +5 -0
  311. package/out/TSTransformer/nodes/transformLogicalOrCoalescingAssignmentExpression.js +91 -0
  312. package/out/TSTransformer/nodes/transformMethodDeclaration.d.ts +5 -0
  313. package/out/TSTransformer/nodes/transformMethodDeclaration.js +82 -0
  314. package/out/TSTransformer/nodes/transformOptionalChain.d.ts +46 -0
  315. package/out/TSTransformer/nodes/transformOptionalChain.js +257 -0
  316. package/out/TSTransformer/nodes/transformParameters.d.ts +8 -0
  317. package/out/TSTransformer/nodes/transformParameters.js +104 -0
  318. package/out/TSTransformer/nodes/transformPropertyName.d.ts +4 -0
  319. package/out/TSTransformer/nodes/transformPropertyName.js +18 -0
  320. package/out/TSTransformer/nodes/transformSourceFile.d.ts +4 -0
  321. package/out/TSTransformer/nodes/transformSourceFile.js +171 -0
  322. package/out/TSTransformer/nodes/transformStatementList.d.ts +7 -0
  323. package/out/TSTransformer/nodes/transformStatementList.js +63 -0
  324. package/out/TSTransformer/nodes/transformWritable.d.ts +9 -0
  325. package/out/TSTransformer/nodes/transformWritable.js +49 -0
  326. package/out/TSTransformer/typeGuards.d.ts +5 -0
  327. package/out/TSTransformer/typeGuards.js +27 -0
  328. package/out/TSTransformer/types.d.ts +9 -0
  329. package/out/TSTransformer/types.js +3 -0
  330. package/out/TSTransformer/util/addIndexDiagnostics.d.ts +3 -0
  331. package/out/TSTransformer/util/addIndexDiagnostics.js +24 -0
  332. package/out/TSTransformer/util/addOneIfArrayType.d.ts +4 -0
  333. package/out/TSTransformer/util/addOneIfArrayType.js +14 -0
  334. package/out/TSTransformer/util/arrayBindingPatternContainsHoists.d.ts +3 -0
  335. package/out/TSTransformer/util/arrayBindingPatternContainsHoists.js +23 -0
  336. package/out/TSTransformer/util/arrayLikeExpressionContainsSpread.d.ts +2 -0
  337. package/out/TSTransformer/util/arrayLikeExpressionContainsSpread.js +17 -0
  338. package/out/TSTransformer/util/assertNever.d.ts +1 -0
  339. package/out/TSTransformer/util/assertNever.js +36 -0
  340. package/out/TSTransformer/util/assignment.d.ts +7 -0
  341. package/out/TSTransformer/util/assignment.js +48 -0
  342. package/out/TSTransformer/util/binding/getAccessorForBindingType.d.ts +6 -0
  343. package/out/TSTransformer/util/binding/getAccessorForBindingType.js +141 -0
  344. package/out/TSTransformer/util/binding/getTargetIdForBindingPattern.d.ts +4 -0
  345. package/out/TSTransformer/util/binding/getTargetIdForBindingPattern.js +15 -0
  346. package/out/TSTransformer/util/binding/objectAccessor.d.ts +4 -0
  347. package/out/TSTransformer/util/binding/objectAccessor.js +39 -0
  348. package/out/TSTransformer/util/bitwise.d.ts +6 -0
  349. package/out/TSTransformer/util/bitwise.js +67 -0
  350. package/out/TSTransformer/util/checkVariableHoist.d.ts +3 -0
  351. package/out/TSTransformer/util/checkVariableHoist.js +33 -0
  352. package/out/TSTransformer/util/cleanModuleName.d.ts +1 -0
  353. package/out/TSTransformer/util/cleanModuleName.js +7 -0
  354. package/out/TSTransformer/util/convertToIndexableExpression.d.ts +3 -0
  355. package/out/TSTransformer/util/convertToIndexableExpression.js +14 -0
  356. package/out/TSTransformer/util/createBinaryFromOperator.d.ts +4 -0
  357. package/out/TSTransformer/util/createBinaryFromOperator.js +54 -0
  358. package/out/TSTransformer/util/createGetService.d.ts +2 -0
  359. package/out/TSTransformer/util/createGetService.js +15 -0
  360. package/out/TSTransformer/util/createHoistDeclaration.d.ts +4 -0
  361. package/out/TSTransformer/util/createHoistDeclaration.js +20 -0
  362. package/out/TSTransformer/util/createImportExpression.d.ts +5 -0
  363. package/out/TSTransformer/util/createImportExpression.js +181 -0
  364. package/out/TSTransformer/util/createStringFromLiteral.d.ts +2 -0
  365. package/out/TSTransformer/util/createStringFromLiteral.js +27 -0
  366. package/out/TSTransformer/util/createTransformServices.d.ts +3 -0
  367. package/out/TSTransformer/util/createTransformServices.js +9 -0
  368. package/out/TSTransformer/util/createTruthinessChecks.d.ts +5 -0
  369. package/out/TSTransformer/util/createTruthinessChecks.js +50 -0
  370. package/out/TSTransformer/util/createTypeCheck.d.ts +2 -0
  371. package/out/TSTransformer/util/createTypeCheck.js +11 -0
  372. package/out/TSTransformer/util/ensureTransformOrder.d.ts +5 -0
  373. package/out/TSTransformer/util/ensureTransformOrder.js +39 -0
  374. package/out/TSTransformer/util/expressionChain.d.ts +3 -0
  375. package/out/TSTransformer/util/expressionChain.js +16 -0
  376. package/out/TSTransformer/util/expressionMightMutate.d.ts +4 -0
  377. package/out/TSTransformer/util/expressionMightMutate.js +57 -0
  378. package/out/TSTransformer/util/findConstructor.d.ts +4 -0
  379. package/out/TSTransformer/util/findConstructor.js +11 -0
  380. package/out/TSTransformer/util/fixupWhitespaceAndDecodeEntities.d.ts +1 -0
  381. package/out/TSTransformer/util/fixupWhitespaceAndDecodeEntities.js +306 -0
  382. package/out/TSTransformer/util/getAddIterableToArrayBuilder.d.ts +6 -0
  383. package/out/TSTransformer/util/getAddIterableToArrayBuilder.js +253 -0
  384. package/out/TSTransformer/util/getAssignableValue.d.ts +3 -0
  385. package/out/TSTransformer/util/getAssignableValue.js +15 -0
  386. package/out/TSTransformer/util/getConstantValueLiteral.d.ts +4 -0
  387. package/out/TSTransformer/util/getConstantValueLiteral.js +19 -0
  388. package/out/TSTransformer/util/getDeclaredVariables.d.ts +2 -0
  389. package/out/TSTransformer/util/getDeclaredVariables.js +37 -0
  390. package/out/TSTransformer/util/getExtendsNode.d.ts +2 -0
  391. package/out/TSTransformer/util/getExtendsNode.js +16 -0
  392. package/out/TSTransformer/util/getFlags.d.ts +1 -0
  393. package/out/TSTransformer/util/getFlags.js +13 -0
  394. package/out/TSTransformer/util/getKindName.d.ts +2 -0
  395. package/out/TSTransformer/util/getKindName.js +61 -0
  396. package/out/TSTransformer/util/getOriginalSymbolOfNode.d.ts +2 -0
  397. package/out/TSTransformer/util/getOriginalSymbolOfNode.js +15 -0
  398. package/out/TSTransformer/util/getSourceFileFromModuleSpecifier.d.ts +3 -0
  399. package/out/TSTransformer/util/getSourceFileFromModuleSpecifier.js +33 -0
  400. package/out/TSTransformer/util/getStatements.d.ts +2 -0
  401. package/out/TSTransformer/util/getStatements.js +11 -0
  402. package/out/TSTransformer/util/hasMultipleDefinitions.d.ts +2 -0
  403. package/out/TSTransformer/util/hasMultipleDefinitions.js +17 -0
  404. package/out/TSTransformer/util/isBlockedByTryStatement.d.ts +3 -0
  405. package/out/TSTransformer/util/isBlockedByTryStatement.js +17 -0
  406. package/out/TSTransformer/util/isMethod.d.ts +4 -0
  407. package/out/TSTransformer/util/isMethod.js +90 -0
  408. package/out/TSTransformer/util/isSymbolMutable.d.ts +3 -0
  409. package/out/TSTransformer/util/isSymbolMutable.js +24 -0
  410. package/out/TSTransformer/util/isSymbolOfValue.d.ts +2 -0
  411. package/out/TSTransformer/util/isSymbolOfValue.js +11 -0
  412. package/out/TSTransformer/util/isUsedAsStatement.d.ts +2 -0
  413. package/out/TSTransformer/util/isUsedAsStatement.js +23 -0
  414. package/out/TSTransformer/util/isValidMethodIndexWithoutCall.d.ts +3 -0
  415. package/out/TSTransformer/util/isValidMethodIndexWithoutCall.js +31 -0
  416. package/out/TSTransformer/util/offset.d.ts +2 -0
  417. package/out/TSTransformer/util/offset.js +44 -0
  418. package/out/TSTransformer/util/pointer.d.ts +13 -0
  419. package/out/TSTransformer/util/pointer.js +46 -0
  420. package/out/TSTransformer/util/spreadDestructuring/index.d.ts +9 -0
  421. package/out/TSTransformer/util/spreadDestructuring/index.js +45 -0
  422. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureArray.d.ts +3 -0
  423. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureArray.js +17 -0
  424. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureGenerator.d.ts +3 -0
  425. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureGenerator.js +33 -0
  426. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureMap.d.ts +3 -0
  427. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureMap.js +34 -0
  428. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureObject.d.ts +3 -0
  429. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureObject.js +41 -0
  430. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureSet.d.ts +3 -0
  431. package/out/TSTransformer/util/spreadDestructuring/spreadDestructureSet.js +28 -0
  432. package/out/TSTransformer/util/traversal.d.ts +7 -0
  433. package/out/TSTransformer/util/traversal.js +57 -0
  434. package/out/TSTransformer/util/types.d.ts +31 -0
  435. package/out/TSTransformer/util/types.js +259 -0
  436. package/out/TSTransformer/util/validateIdentifier.d.ts +3 -0
  437. package/out/TSTransformer/util/validateIdentifier.js +18 -0
  438. package/out/TSTransformer/util/validateMethodAssignment.d.ts +3 -0
  439. package/out/TSTransformer/util/validateMethodAssignment.js +81 -0
  440. package/out/TSTransformer/util/validateNotAny.d.ts +3 -0
  441. package/out/TSTransformer/util/validateNotAny.js +37 -0
  442. package/out/TSTransformer/util/valueToIdStr.d.ts +2 -0
  443. package/out/TSTransformer/util/valueToIdStr.js +29 -0
  444. package/out/TSTransformer/util/wrapExpressionStatement.d.ts +2 -0
  445. package/out/TSTransformer/util/wrapExpressionStatement.js +22 -0
  446. package/out/TSTransformer/util/wrapReturnIfLuaTuple.d.ts +4 -0
  447. package/out/TSTransformer/util/wrapReturnIfLuaTuple.js +56 -0
  448. package/out/TSTransformer/util/wrapStatementsAsGenerator.d.ts +4 -0
  449. package/out/TSTransformer/util/wrapStatementsAsGenerator.js +19 -0
  450. package/package.json +72 -0
@@ -0,0 +1,2068 @@
1
+ --[[
2
+ An implementation of Promises similar to Promise/A+.
3
+ ]]
4
+
5
+ local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s"
6
+ local ERROR_NON_LIST = "Please pass a list of promises to %s"
7
+ local ERROR_NON_FUNCTION = "Please pass a handler function to %s!"
8
+ local MODE_KEY_METATABLE = { __mode = "k" }
9
+
10
+ local function isCallable(value)
11
+ if type(value) == "function" then
12
+ return true
13
+ end
14
+
15
+ if type(value) == "table" then
16
+ local metatable = getmetatable(value)
17
+ if metatable and type(rawget(metatable, "__call")) == "function" then
18
+ return true
19
+ end
20
+ end
21
+
22
+ return false
23
+ end
24
+
25
+ --[[
26
+ Creates an enum dictionary with some metamethods to prevent common mistakes.
27
+ ]]
28
+ local function makeEnum(enumName, members)
29
+ local enum = {}
30
+
31
+ for _, memberName in ipairs(members) do
32
+ enum[memberName] = memberName
33
+ end
34
+
35
+ return setmetatable(enum, {
36
+ __index = function(_, k)
37
+ error(string.format("%s is not in %s!", k, enumName), 2)
38
+ end,
39
+ __newindex = function()
40
+ error(string.format("Creating new members in %s is not allowed!", enumName), 2)
41
+ end,
42
+ })
43
+ end
44
+
45
+ --[=[
46
+ An object to represent runtime errors that occur during execution.
47
+ Promises that experience an error like this will be rejected with
48
+ an instance of this object.
49
+
50
+ @class Error
51
+ ]=]
52
+ local Error
53
+ do
54
+ Error = {
55
+ Kind = makeEnum("Promise.Error.Kind", {
56
+ "ExecutionError",
57
+ "AlreadyCancelled",
58
+ "NotResolvedInTime",
59
+ "TimedOut",
60
+ }),
61
+ }
62
+ Error.__index = Error
63
+
64
+ function Error.new(options, parent)
65
+ options = options or {}
66
+ return setmetatable({
67
+ error = tostring(options.error) or "[This error has no error text.]",
68
+ trace = options.trace,
69
+ context = options.context,
70
+ kind = options.kind,
71
+ parent = parent,
72
+ createdTick = os.clock(),
73
+ createdTrace = debug.traceback(),
74
+ }, Error)
75
+ end
76
+
77
+ function Error.is(anything)
78
+ if type(anything) == "table" then
79
+ local metatable = getmetatable(anything)
80
+
81
+ if type(metatable) == "table" then
82
+ return rawget(anything, "error") ~= nil and type(rawget(metatable, "extend")) == "function"
83
+ end
84
+ end
85
+
86
+ return false
87
+ end
88
+
89
+ function Error.isKind(anything, kind)
90
+ assert(kind ~= nil, "Argument #2 to Promise.Error.isKind must not be nil")
91
+
92
+ return Error.is(anything) and anything.kind == kind
93
+ end
94
+
95
+ function Error:extend(options)
96
+ options = options or {}
97
+
98
+ options.kind = options.kind or self.kind
99
+
100
+ return Error.new(options, self)
101
+ end
102
+
103
+ function Error:getErrorChain()
104
+ local runtimeErrors = { self }
105
+
106
+ while runtimeErrors[#runtimeErrors].parent do
107
+ table.insert(runtimeErrors, runtimeErrors[#runtimeErrors].parent)
108
+ end
109
+
110
+ return runtimeErrors
111
+ end
112
+
113
+ function Error:__tostring()
114
+ local errorStrings = {
115
+ string.format("-- Promise.Error(%s) --", self.kind or "?"),
116
+ }
117
+
118
+ for _, runtimeError in ipairs(self:getErrorChain()) do
119
+ table.insert(
120
+ errorStrings,
121
+ table.concat({
122
+ runtimeError.trace or runtimeError.error,
123
+ runtimeError.context,
124
+ }, "\n")
125
+ )
126
+ end
127
+
128
+ return table.concat(errorStrings, "\n")
129
+ end
130
+ end
131
+
132
+ --[[
133
+ Packs a number of arguments into a table and returns its length.
134
+
135
+ Used to cajole varargs without dropping sparse values.
136
+ ]]
137
+ local function pack(...)
138
+ return select("#", ...), { ... }
139
+ end
140
+
141
+ --[[
142
+ Returns first value (success), and packs all following values.
143
+ ]]
144
+ local function packResult(success, ...)
145
+ return success, select("#", ...), { ... }
146
+ end
147
+
148
+ local function makeErrorHandler(traceback)
149
+ assert(traceback ~= nil, "traceback is nil")
150
+
151
+ return function(err)
152
+ -- If the error object is already a table, forward it directly.
153
+ -- Should we extend the error here and add our own trace?
154
+
155
+ if type(err) == "table" then
156
+ return err
157
+ end
158
+
159
+ return Error.new({
160
+ error = err,
161
+ kind = Error.Kind.ExecutionError,
162
+ trace = debug.traceback(tostring(err), 2),
163
+ context = "Promise created at:\n\n" .. traceback,
164
+ })
165
+ end
166
+ end
167
+
168
+ --[[
169
+ Calls a Promise executor with error handling.
170
+ ]]
171
+ local function runExecutor(traceback, callback, ...)
172
+ return packResult(xpcall(callback, makeErrorHandler(traceback), ...))
173
+ end
174
+
175
+ --[[
176
+ Creates a function that invokes a callback with correct error handling and
177
+ resolution mechanisms.
178
+ ]]
179
+ local function createAdvancer(traceback, callback, resolve, reject)
180
+ return function(...)
181
+ local ok, resultLength, result = runExecutor(traceback, callback, ...)
182
+
183
+ if ok then
184
+ resolve(unpack(result, 1, resultLength))
185
+ else
186
+ reject(result[1])
187
+ end
188
+ end
189
+ end
190
+
191
+ local function isEmpty(t)
192
+ return next(t) == nil
193
+ end
194
+
195
+ --[=[
196
+ An enum value used to represent the Promise's status.
197
+ @interface Status
198
+ @tag enum
199
+ @within Promise
200
+ .Started "Started" -- The Promise is executing, and not settled yet.
201
+ .Resolved "Resolved" -- The Promise finished successfully.
202
+ .Rejected "Rejected" -- The Promise was rejected.
203
+ .Cancelled "Cancelled" -- The Promise was cancelled before it finished.
204
+ ]=]
205
+ --[=[
206
+ @prop Status Status
207
+ @within Promise
208
+ @readonly
209
+ @tag enums
210
+ A table containing all members of the `Status` enum, e.g., `Promise.Status.Resolved`.
211
+ ]=]
212
+ --[=[
213
+ A Promise is an object that represents a value that will exist in the future, but doesn't right now.
214
+ Promises allow you to then attach callbacks that can run once the value becomes available (known as *resolving*),
215
+ or if an error has occurred (known as *rejecting*).
216
+
217
+ @class Promise
218
+ @__index prototype
219
+ ]=]
220
+ local Promise = {
221
+ Error = Error,
222
+ Status = makeEnum("Promise.Status", { "Started", "Resolved", "Rejected", "Cancelled" }),
223
+ _getTime = os.clock,
224
+ _timeEvent = game:GetService("RunService").Heartbeat,
225
+ _unhandledRejectionCallbacks = {},
226
+ }
227
+ Promise.prototype = {}
228
+ Promise.__index = Promise.prototype
229
+
230
+ function Promise._new(traceback, callback, parent)
231
+ if parent ~= nil and not Promise.is(parent) then
232
+ error("Argument #2 to Promise.new must be a promise or nil", 2)
233
+ end
234
+
235
+ local self = {
236
+ -- The executor thread.
237
+ _thread = nil,
238
+
239
+ -- Used to locate where a promise was created
240
+ _source = traceback,
241
+
242
+ _status = Promise.Status.Started,
243
+
244
+ -- A table containing a list of all results, whether success or failure.
245
+ -- Only valid if _status is set to something besides Started
246
+ _values = nil,
247
+
248
+ -- Lua doesn't like sparse arrays very much, so we explicitly store the
249
+ -- length of _values to handle middle nils.
250
+ _valuesLength = -1,
251
+
252
+ -- Tracks if this Promise has no error observers..
253
+ _unhandledRejection = true,
254
+
255
+ -- Queues representing functions we should invoke when we update!
256
+ _queuedResolve = {},
257
+ _queuedReject = {},
258
+ _queuedFinally = {},
259
+
260
+ -- The function to run when/if this promise is cancelled.
261
+ _cancellationHook = nil,
262
+
263
+ -- The "parent" of this promise in a promise chain. Required for
264
+ -- cancellation propagation upstream.
265
+ _parent = parent,
266
+
267
+ -- Consumers are Promises that have chained onto this one.
268
+ -- We track them for cancellation propagation downstream.
269
+ _consumers = setmetatable({}, MODE_KEY_METATABLE),
270
+ }
271
+
272
+ if parent and parent._status == Promise.Status.Started then
273
+ parent._consumers[self] = true
274
+ end
275
+
276
+ setmetatable(self, Promise)
277
+
278
+ local function resolve(...)
279
+ self:_resolve(...)
280
+ end
281
+
282
+ local function reject(...)
283
+ self:_reject(...)
284
+ end
285
+
286
+ local function onCancel(cancellationHook)
287
+ if cancellationHook then
288
+ if self._status == Promise.Status.Cancelled then
289
+ cancellationHook()
290
+ else
291
+ self._cancellationHook = cancellationHook
292
+ end
293
+ end
294
+
295
+ return self._status == Promise.Status.Cancelled
296
+ end
297
+
298
+ self._thread = coroutine.create(function()
299
+ local ok, _, result = runExecutor(self._source, callback, resolve, reject, onCancel)
300
+
301
+ if not ok then
302
+ reject(result[1])
303
+ end
304
+ end)
305
+
306
+ task.spawn(self._thread)
307
+
308
+ return self
309
+ end
310
+
311
+ --[=[
312
+ Construct a new Promise that will be resolved or rejected with the given callbacks.
313
+
314
+ If you `resolve` with a Promise, it will be chained onto.
315
+
316
+ You can safely yield within the executor function and it will not block the creating thread.
317
+
318
+ ```lua
319
+ local myFunction()
320
+ return Promise.new(function(resolve, reject, onCancel)
321
+ wait(1)
322
+ resolve("Hello world!")
323
+ end)
324
+ end
325
+
326
+ myFunction():andThen(print)
327
+ ```
328
+
329
+ You do not need to use `pcall` within a Promise. Errors that occur during execution will be caught and turned into a rejection automatically. If `error()` is called with a table, that table will be the rejection value. Otherwise, string errors will be converted into `Promise.Error(Promise.Error.Kind.ExecutionError)` objects for tracking debug information.
330
+
331
+ You may register an optional cancellation hook by using the `onCancel` argument:
332
+
333
+ * This should be used to abort any ongoing operations leading up to the promise being settled.
334
+ * Call the `onCancel` function with a function callback as its only argument to set a hook which will in turn be called when/if the promise is cancelled.
335
+ * `onCancel` returns `true` if the Promise was already cancelled when you called `onCancel`.
336
+ * Calling `onCancel` with no argument will not override a previously set cancellation hook, but it will still return `true` if the Promise is currently cancelled.
337
+ * You can set the cancellation hook at any time before resolving.
338
+ * When a promise is cancelled, calls to `resolve` or `reject` will be ignored, regardless of if you set a cancellation hook or not.
339
+
340
+ :::caution
341
+ If the Promise is cancelled, the `executor` thread is closed with `coroutine.close` after the cancellation hook is called.
342
+
343
+ You must perform any cleanup code in the cancellation hook: any time your executor yields, it **may never resume**.
344
+ :::
345
+
346
+ @param executor (resolve: (...: any) -> (), reject: (...: any) -> (), onCancel: (abortHandler?: () -> ()) -> boolean) -> ()
347
+ @return Promise
348
+ ]=]
349
+ function Promise.new(executor)
350
+ return Promise._new(debug.traceback(nil, 2), executor)
351
+ end
352
+
353
+ function Promise:__tostring()
354
+ return string.format("Promise(%s)", self._status)
355
+ end
356
+
357
+ --[=[
358
+ The same as [Promise.new](/api/Promise#new), except execution begins after the next `Heartbeat` event.
359
+
360
+ This is a spiritual replacement for `spawn`, but it does not suffer from the same [issues](https://eryn.io/gist/3db84579866c099cdd5bb2ff37947cec) as `spawn`.
361
+
362
+ ```lua
363
+ local function waitForChild(instance, childName, timeout)
364
+ return Promise.defer(function(resolve, reject)
365
+ local child = instance:WaitForChild(childName, timeout)
366
+
367
+ ;(child and resolve or reject)(child)
368
+ end)
369
+ end
370
+ ```
371
+
372
+ @param executor (resolve: (...: any) -> (), reject: (...: any) -> (), onCancel: (abortHandler?: () -> ()) -> boolean) -> ()
373
+ @return Promise
374
+ ]=]
375
+ function Promise.defer(executor)
376
+ local traceback = debug.traceback(nil, 2)
377
+ local promise
378
+ promise = Promise._new(traceback, function(resolve, reject, onCancel)
379
+ local connection
380
+ connection = Promise._timeEvent:Connect(function()
381
+ connection:Disconnect()
382
+ local ok, _, result = runExecutor(traceback, executor, resolve, reject, onCancel)
383
+
384
+ if not ok then
385
+ reject(result[1])
386
+ end
387
+ end)
388
+ end)
389
+
390
+ return promise
391
+ end
392
+
393
+ -- Backwards compatibility
394
+ Promise.async = Promise.defer
395
+
396
+ --[=[
397
+ Creates an immediately resolved Promise with the given value.
398
+
399
+ ```lua
400
+ -- Example using Promise.resolve to deliver cached values:
401
+ function getSomething(name)
402
+ if cache[name] then
403
+ return Promise.resolve(cache[name])
404
+ else
405
+ return Promise.new(function(resolve, reject)
406
+ local thing = getTheThing()
407
+ cache[name] = thing
408
+
409
+ resolve(thing)
410
+ end)
411
+ end
412
+ end
413
+ ```
414
+
415
+ @param ... any
416
+ @return Promise<...any>
417
+ ]=]
418
+ function Promise.resolve(...)
419
+ local length, values = pack(...)
420
+ return Promise._new(debug.traceback(nil, 2), function(resolve)
421
+ resolve(unpack(values, 1, length))
422
+ end)
423
+ end
424
+
425
+ --[=[
426
+ Creates an immediately rejected Promise with the given value.
427
+
428
+ :::caution
429
+ Something needs to consume this rejection (i.e. `:catch()` it), otherwise it will emit an unhandled Promise rejection warning on the next frame. Thus, you should not create and store rejected Promises for later use. Only create them on-demand as needed.
430
+ :::
431
+
432
+ @param ... any
433
+ @return Promise<...any>
434
+ ]=]
435
+ function Promise.reject(...)
436
+ local length, values = pack(...)
437
+ return Promise._new(debug.traceback(nil, 2), function(_, reject)
438
+ reject(unpack(values, 1, length))
439
+ end)
440
+ end
441
+
442
+ --[[
443
+ Runs a non-promise-returning function as a Promise with the
444
+ given arguments.
445
+ ]]
446
+ function Promise._try(traceback, callback, ...)
447
+ local valuesLength, values = pack(...)
448
+
449
+ return Promise._new(traceback, function(resolve)
450
+ resolve(callback(unpack(values, 1, valuesLength)))
451
+ end)
452
+ end
453
+
454
+ --[=[
455
+ Begins a Promise chain, calling a function and returning a Promise resolving with its return value. If the function errors, the returned Promise will be rejected with the error. You can safely yield within the Promise.try callback.
456
+
457
+ :::info
458
+ `Promise.try` is similar to [Promise.promisify](#promisify), except the callback is invoked immediately instead of returning a new function.
459
+ :::
460
+
461
+ ```lua
462
+ Promise.try(function()
463
+ return math.random(1, 2) == 1 and "ok" or error("Oh an error!")
464
+ end)
465
+ :andThen(function(text)
466
+ print(text)
467
+ end)
468
+ :catch(function(err)
469
+ warn("Something went wrong")
470
+ end)
471
+ ```
472
+
473
+ @param callback (...: T...) -> ...any
474
+ @param ... T... -- Additional arguments passed to `callback`
475
+ @return Promise
476
+ ]=]
477
+ function Promise.try(callback, ...)
478
+ return Promise._try(debug.traceback(nil, 2), callback, ...)
479
+ end
480
+
481
+ --[[
482
+ Returns a new promise that:
483
+ * is resolved when all input promises resolve
484
+ * is rejected if ANY input promises reject
485
+ ]]
486
+ function Promise._all(traceback, promises, amount)
487
+ if type(promises) ~= "table" then
488
+ error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
489
+ end
490
+
491
+ -- We need to check that each value is a promise here so that we can produce
492
+ -- a proper error rather than a rejected promise with our error.
493
+ for i, promise in pairs(promises) do
494
+ if not Promise.is(promise) then
495
+ error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
496
+ end
497
+ end
498
+
499
+ -- If there are no values then return an already resolved promise.
500
+ if #promises == 0 or amount == 0 then
501
+ return Promise.resolve({})
502
+ end
503
+
504
+ return Promise._new(traceback, function(resolve, reject, onCancel)
505
+ -- An array to contain our resolved values from the given promises.
506
+ local resolvedValues = {}
507
+ local newPromises = {}
508
+
509
+ -- Keep a count of resolved promises because just checking the resolved
510
+ -- values length wouldn't account for promises that resolve with nil.
511
+ local resolvedCount = 0
512
+ local rejectedCount = 0
513
+ local done = false
514
+
515
+ local function cancel()
516
+ for _, promise in ipairs(newPromises) do
517
+ promise:cancel()
518
+ end
519
+ end
520
+
521
+ -- Called when a single value is resolved and resolves if all are done.
522
+ local function resolveOne(i, ...)
523
+ if done then
524
+ return
525
+ end
526
+
527
+ resolvedCount = resolvedCount + 1
528
+
529
+ if amount == nil then
530
+ resolvedValues[i] = ...
531
+ else
532
+ resolvedValues[resolvedCount] = ...
533
+ end
534
+
535
+ if resolvedCount >= (amount or #promises) then
536
+ done = true
537
+ resolve(resolvedValues)
538
+ cancel()
539
+ end
540
+ end
541
+
542
+ onCancel(cancel)
543
+
544
+ -- We can assume the values inside `promises` are all promises since we
545
+ -- checked above.
546
+ for i, promise in ipairs(promises) do
547
+ newPromises[i] = promise:andThen(function(...)
548
+ resolveOne(i, ...)
549
+ end, function(...)
550
+ rejectedCount = rejectedCount + 1
551
+
552
+ if amount == nil or #promises - rejectedCount < amount then
553
+ cancel()
554
+ done = true
555
+
556
+ reject(...)
557
+ end
558
+ end)
559
+ end
560
+
561
+ if done then
562
+ cancel()
563
+ end
564
+ end)
565
+ end
566
+
567
+ --[=[
568
+ Accepts an array of Promises and returns a new promise that:
569
+ * is resolved after all input promises resolve.
570
+ * is rejected if *any* input promises reject.
571
+
572
+ :::info
573
+ Only the first return value from each promise will be present in the resulting array.
574
+ :::
575
+
576
+ After any input Promise rejects, all other input Promises that are still pending will be cancelled if they have no other consumers.
577
+
578
+ ```lua
579
+ local promises = {
580
+ returnsAPromise("example 1"),
581
+ returnsAPromise("example 2"),
582
+ returnsAPromise("example 3"),
583
+ }
584
+
585
+ return Promise.all(promises)
586
+ ```
587
+
588
+ @param promises {Promise<T>}
589
+ @return Promise<{T}>
590
+ ]=]
591
+ function Promise.all(promises)
592
+ return Promise._all(debug.traceback(nil, 2), promises)
593
+ end
594
+
595
+ --[=[
596
+ Folds an array of values or promises into a single value. The array is traversed sequentially.
597
+
598
+ The reducer function can return a promise or value directly. Each iteration receives the resolved value from the previous, and the first receives your defined initial value.
599
+
600
+ The folding will stop at the first rejection encountered.
601
+ ```lua
602
+ local basket = {"blueberry", "melon", "pear", "melon"}
603
+ Promise.fold(basket, function(cost, fruit)
604
+ if fruit == "blueberry" then
605
+ return cost -- blueberries are free!
606
+ else
607
+ -- call a function that returns a promise with the fruit price
608
+ return fetchPrice(fruit):andThen(function(fruitCost)
609
+ return cost + fruitCost
610
+ end)
611
+ end
612
+ end, 0)
613
+ ```
614
+
615
+ @since v3.1.0
616
+ @param list {T | Promise<T>}
617
+ @param reducer (accumulator: U, value: T, index: number) -> U | Promise<U>
618
+ @param initialValue U
619
+ ]=]
620
+ function Promise.fold(list, reducer, initialValue)
621
+ assert(type(list) == "table", "Bad argument #1 to Promise.fold: must be a table")
622
+ assert(isCallable(reducer), "Bad argument #2 to Promise.fold: must be a function")
623
+
624
+ local accumulator = Promise.resolve(initialValue)
625
+ return Promise.each(list, function(resolvedElement, i)
626
+ accumulator = accumulator:andThen(function(previousValueResolved)
627
+ return reducer(previousValueResolved, resolvedElement, i)
628
+ end)
629
+ end):andThen(function()
630
+ return accumulator
631
+ end)
632
+ end
633
+
634
+ --[=[
635
+ Accepts an array of Promises and returns a Promise that is resolved as soon as `count` Promises are resolved from the input array. The resolved array values are in the order that the Promises resolved in. When this Promise resolves, all other pending Promises are cancelled if they have no other consumers.
636
+
637
+ `count` 0 results in an empty array. The resultant array will never have more than `count` elements.
638
+
639
+ ```lua
640
+ local promises = {
641
+ returnsAPromise("example 1"),
642
+ returnsAPromise("example 2"),
643
+ returnsAPromise("example 3"),
644
+ }
645
+
646
+ return Promise.some(promises, 2) -- Only resolves with first 2 promises to resolve
647
+ ```
648
+
649
+ @param promises {Promise<T>}
650
+ @param count number
651
+ @return Promise<{T}>
652
+ ]=]
653
+ function Promise.some(promises, count)
654
+ assert(type(count) == "number", "Bad argument #2 to Promise.some: must be a number")
655
+
656
+ return Promise._all(debug.traceback(nil, 2), promises, count)
657
+ end
658
+
659
+ --[=[
660
+ Accepts an array of Promises and returns a Promise that is resolved as soon as *any* of the input Promises resolves. It will reject only if *all* input Promises reject. As soon as one Promises resolves, all other pending Promises are cancelled if they have no other consumers.
661
+
662
+ Resolves directly with the value of the first resolved Promise. This is essentially [[Promise.some]] with `1` count, except the Promise resolves with the value directly instead of an array with one element.
663
+
664
+ ```lua
665
+ local promises = {
666
+ returnsAPromise("example 1"),
667
+ returnsAPromise("example 2"),
668
+ returnsAPromise("example 3"),
669
+ }
670
+
671
+ return Promise.any(promises) -- Resolves with first value to resolve (only rejects if all 3 rejected)
672
+ ```
673
+
674
+ @param promises {Promise<T>}
675
+ @return Promise<T>
676
+ ]=]
677
+ function Promise.any(promises)
678
+ return Promise._all(debug.traceback(nil, 2), promises, 1):andThen(function(values)
679
+ return values[1]
680
+ end)
681
+ end
682
+
683
+ --[=[
684
+ Accepts an array of Promises and returns a new Promise that resolves with an array of in-place Statuses when all input Promises have settled. This is equivalent to mapping `promise:finally` over the array of Promises.
685
+
686
+ ```lua
687
+ local promises = {
688
+ returnsAPromise("example 1"),
689
+ returnsAPromise("example 2"),
690
+ returnsAPromise("example 3"),
691
+ }
692
+
693
+ return Promise.allSettled(promises)
694
+ ```
695
+
696
+ @param promises {Promise<T>}
697
+ @return Promise<{Status}>
698
+ ]=]
699
+ function Promise.allSettled(promises)
700
+ if type(promises) ~= "table" then
701
+ error(string.format(ERROR_NON_LIST, "Promise.allSettled"), 2)
702
+ end
703
+
704
+ -- We need to check that each value is a promise here so that we can produce
705
+ -- a proper error rather than a rejected promise with our error.
706
+ for i, promise in pairs(promises) do
707
+ if not Promise.is(promise) then
708
+ error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.allSettled", tostring(i)), 2)
709
+ end
710
+ end
711
+
712
+ -- If there are no values then return an already resolved promise.
713
+ if #promises == 0 then
714
+ return Promise.resolve({})
715
+ end
716
+
717
+ return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
718
+ -- An array to contain our resolved values from the given promises.
719
+ local fates = {}
720
+ local newPromises = {}
721
+
722
+ -- Keep a count of resolved promises because just checking the resolved
723
+ -- values length wouldn't account for promises that resolve with nil.
724
+ local finishedCount = 0
725
+
726
+ -- Called when a single value is resolved and resolves if all are done.
727
+ local function resolveOne(i, ...)
728
+ finishedCount = finishedCount + 1
729
+
730
+ fates[i] = ...
731
+
732
+ if finishedCount >= #promises then
733
+ resolve(fates)
734
+ end
735
+ end
736
+
737
+ onCancel(function()
738
+ for _, promise in ipairs(newPromises) do
739
+ promise:cancel()
740
+ end
741
+ end)
742
+
743
+ -- We can assume the values inside `promises` are all promises since we
744
+ -- checked above.
745
+ for i, promise in ipairs(promises) do
746
+ newPromises[i] = promise:finally(function(...)
747
+ resolveOne(i, ...)
748
+ end)
749
+ end
750
+ end)
751
+ end
752
+
753
+ --[=[
754
+ Accepts an array of Promises and returns a new promise that is resolved or rejected as soon as any Promise in the array resolves or rejects.
755
+
756
+ :::warning
757
+ If the first Promise to settle from the array settles with a rejection, the resulting Promise from `race` will reject.
758
+
759
+ If you instead want to tolerate rejections, and only care about at least one Promise resolving, you should use [Promise.any](#any) or [Promise.some](#some) instead.
760
+ :::
761
+
762
+ All other Promises that don't win the race will be cancelled if they have no other consumers.
763
+
764
+ ```lua
765
+ local promises = {
766
+ returnsAPromise("example 1"),
767
+ returnsAPromise("example 2"),
768
+ returnsAPromise("example 3"),
769
+ }
770
+
771
+ return Promise.race(promises) -- Only returns 1st value to resolve or reject
772
+ ```
773
+
774
+ @param promises {Promise<T>}
775
+ @return Promise<T>
776
+ ]=]
777
+ function Promise.race(promises)
778
+ assert(type(promises) == "table", string.format(ERROR_NON_LIST, "Promise.race"))
779
+
780
+ for i, promise in pairs(promises) do
781
+ assert(Promise.is(promise), string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.race", tostring(i)))
782
+ end
783
+
784
+ return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
785
+ local newPromises = {}
786
+ local finished = false
787
+
788
+ local function cancel()
789
+ for _, promise in ipairs(newPromises) do
790
+ promise:cancel()
791
+ end
792
+ end
793
+
794
+ local function finalize(callback)
795
+ return function(...)
796
+ cancel()
797
+ finished = true
798
+ return callback(...)
799
+ end
800
+ end
801
+
802
+ if onCancel(finalize(reject)) then
803
+ return
804
+ end
805
+
806
+ for i, promise in ipairs(promises) do
807
+ newPromises[i] = promise:andThen(finalize(resolve), finalize(reject))
808
+ end
809
+
810
+ if finished then
811
+ cancel()
812
+ end
813
+ end)
814
+ end
815
+
816
+ --[=[
817
+ Iterates serially over the given an array of values, calling the predicate callback on each value before continuing.
818
+
819
+ If the predicate returns a Promise, we wait for that Promise to resolve before moving on to the next item
820
+ in the array.
821
+
822
+ :::info
823
+ `Promise.each` is similar to `Promise.all`, except the Promises are ran in order instead of all at once.
824
+
825
+ But because Promises are eager, by the time they are created, they're already running. Thus, we need a way to defer creation of each Promise until a later time.
826
+
827
+ The predicate function exists as a way for us to operate on our data instead of creating a new closure for each Promise. If you would prefer, you can pass in an array of functions, and in the predicate, call the function and return its return value.
828
+ :::
829
+
830
+ ```lua
831
+ Promise.each({
832
+ "foo",
833
+ "bar",
834
+ "baz",
835
+ "qux"
836
+ }, function(value, index)
837
+ return Promise.delay(1):andThen(function()
838
+ print(("%d) Got %s!"):format(index, value))
839
+ end)
840
+ end)
841
+
842
+ --[[
843
+ (1 second passes)
844
+ > 1) Got foo!
845
+ (1 second passes)
846
+ > 2) Got bar!
847
+ (1 second passes)
848
+ > 3) Got baz!
849
+ (1 second passes)
850
+ > 4) Got qux!
851
+ ]]
852
+ ```
853
+
854
+ If the Promise a predicate returns rejects, the Promise from `Promise.each` is also rejected with the same value.
855
+
856
+ If the array of values contains a Promise, when we get to that point in the list, we wait for the Promise to resolve before calling the predicate with the value.
857
+
858
+ If a Promise in the array of values is already Rejected when `Promise.each` is called, `Promise.each` rejects with that value immediately (the predicate callback will never be called even once). If a Promise in the list is already Cancelled when `Promise.each` is called, `Promise.each` rejects with `Promise.Error(Promise.Error.Kind.AlreadyCancelled`). If a Promise in the array of values is Started at first, but later rejects, `Promise.each` will reject with that value and iteration will not continue once iteration encounters that value.
859
+
860
+ Returns a Promise containing an array of the returned/resolved values from the predicate for each item in the array of values.
861
+
862
+ If this Promise returned from `Promise.each` rejects or is cancelled for any reason, the following are true:
863
+ - Iteration will not continue.
864
+ - Any Promises within the array of values will now be cancelled if they have no other consumers.
865
+ - The Promise returned from the currently active predicate will be cancelled if it hasn't resolved yet.
866
+
867
+ @since 3.0.0
868
+ @param list {T | Promise<T>}
869
+ @param predicate (value: T, index: number) -> U | Promise<U>
870
+ @return Promise<{U}>
871
+ ]=]
872
+ function Promise.each(list, predicate)
873
+ assert(type(list) == "table", string.format(ERROR_NON_LIST, "Promise.each"))
874
+ assert(isCallable(predicate), string.format(ERROR_NON_FUNCTION, "Promise.each"))
875
+
876
+ return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
877
+ local results = {}
878
+ local promisesToCancel = {}
879
+
880
+ local cancelled = false
881
+
882
+ local function cancel()
883
+ for _, promiseToCancel in ipairs(promisesToCancel) do
884
+ promiseToCancel:cancel()
885
+ end
886
+ end
887
+
888
+ onCancel(function()
889
+ cancelled = true
890
+
891
+ cancel()
892
+ end)
893
+
894
+ -- We need to preprocess the list of values and look for Promises.
895
+ -- If we find some, we must register our andThen calls now, so that those Promises have a consumer
896
+ -- from us registered. If we don't do this, those Promises might get cancelled by something else
897
+ -- before we get to them in the series because it's not possible to tell that we plan to use it
898
+ -- unless we indicate it here.
899
+
900
+ local preprocessedList = {}
901
+
902
+ for index, value in ipairs(list) do
903
+ if Promise.is(value) then
904
+ if value:getStatus() == Promise.Status.Cancelled then
905
+ cancel()
906
+ return reject(Error.new({
907
+ error = "Promise is cancelled",
908
+ kind = Error.Kind.AlreadyCancelled,
909
+ context = string.format(
910
+ "The Promise that was part of the array at index %d passed into Promise.each was already cancelled when Promise.each began.\n\nThat Promise was created at:\n\n%s",
911
+ index,
912
+ value._source
913
+ ),
914
+ }))
915
+ elseif value:getStatus() == Promise.Status.Rejected then
916
+ cancel()
917
+ return reject(select(2, value:await()))
918
+ end
919
+
920
+ -- Chain a new Promise from this one so we only cancel ours
921
+ local ourPromise = value:andThen(function(...)
922
+ return ...
923
+ end)
924
+
925
+ table.insert(promisesToCancel, ourPromise)
926
+ preprocessedList[index] = ourPromise
927
+ else
928
+ preprocessedList[index] = value
929
+ end
930
+ end
931
+
932
+ for index, value in ipairs(preprocessedList) do
933
+ if Promise.is(value) then
934
+ local success
935
+ success, value = value:await()
936
+
937
+ if not success then
938
+ cancel()
939
+ return reject(value)
940
+ end
941
+ end
942
+
943
+ if cancelled then
944
+ return
945
+ end
946
+
947
+ local predicatePromise = Promise.resolve(predicate(value, index))
948
+
949
+ table.insert(promisesToCancel, predicatePromise)
950
+
951
+ local success, result = predicatePromise:await()
952
+
953
+ if not success then
954
+ cancel()
955
+ return reject(result)
956
+ end
957
+
958
+ results[index] = result
959
+ end
960
+
961
+ resolve(results)
962
+ end)
963
+ end
964
+
965
+ --[=[
966
+ Checks whether the given object is a Promise via duck typing. This only checks if the object is a table and has an `andThen` method.
967
+
968
+ @param object any
969
+ @return boolean -- `true` if the given `object` is a Promise.
970
+ ]=]
971
+ function Promise.is(object)
972
+ if type(object) ~= "table" then
973
+ return false
974
+ end
975
+
976
+ local objectMetatable = getmetatable(object)
977
+
978
+ if objectMetatable == Promise then
979
+ -- The Promise came from this library.
980
+ return true
981
+ elseif objectMetatable == nil then
982
+ -- No metatable, but we should still chain onto tables with andThen methods
983
+ return isCallable(object.andThen)
984
+ elseif
985
+ type(objectMetatable) == "table"
986
+ and type(rawget(objectMetatable, "__index")) == "table"
987
+ and isCallable(rawget(rawget(objectMetatable, "__index"), "andThen"))
988
+ then
989
+ -- Maybe this came from a different or older Promise library.
990
+ return true
991
+ end
992
+
993
+ return false
994
+ end
995
+
996
+ --[=[
997
+ Wraps a function that yields into one that returns a Promise.
998
+
999
+ Any errors that occur while executing the function will be turned into rejections.
1000
+
1001
+ :::info
1002
+ `Promise.promisify` is similar to [Promise.try](#try), except the callback is returned as a callable function instead of being invoked immediately.
1003
+ :::
1004
+
1005
+ ```lua
1006
+ local sleep = Promise.promisify(wait)
1007
+
1008
+ sleep(1):andThen(print)
1009
+ ```
1010
+
1011
+ ```lua
1012
+ local isPlayerInGroup = Promise.promisify(function(player, groupId)
1013
+ return player:IsInGroup(groupId)
1014
+ end)
1015
+ ```
1016
+
1017
+ @param callback (...: any) -> ...any
1018
+ @return (...: any) -> Promise
1019
+ ]=]
1020
+ function Promise.promisify(callback)
1021
+ return function(...)
1022
+ return Promise._try(debug.traceback(nil, 2), callback, ...)
1023
+ end
1024
+ end
1025
+
1026
+ --[=[
1027
+ Returns a Promise that resolves after `seconds` seconds have passed. The Promise resolves with the actual amount of time that was waited.
1028
+
1029
+ This function is **not** a wrapper around `wait`. `Promise.delay` uses a custom scheduler which provides more accurate timing. As an optimization, cancelling this Promise instantly removes the task from the scheduler.
1030
+
1031
+ :::warning
1032
+ Passing `NaN`, infinity, or a number less than 1/60 is equivalent to passing 1/60.
1033
+ :::
1034
+
1035
+ ```lua
1036
+ Promise.delay(5):andThenCall(print, "This prints after 5 seconds")
1037
+ ```
1038
+
1039
+ @function delay
1040
+ @within Promise
1041
+ @param seconds number
1042
+ @return Promise<number>
1043
+ ]=]
1044
+ do
1045
+ -- uses a sorted doubly linked list (queue) to achieve O(1) remove operations and O(n) for insert
1046
+
1047
+ -- the initial node in the linked list
1048
+ local first
1049
+ local connection
1050
+
1051
+ function Promise.delay(seconds)
1052
+ assert(type(seconds) == "number", "Bad argument #1 to Promise.delay, must be a number.")
1053
+ -- If seconds is -INF, INF, NaN, or less than 1 / 60, assume seconds is 1 / 60.
1054
+ -- This mirrors the behavior of wait()
1055
+ if not (seconds >= 1 / 60) or seconds == math.huge then
1056
+ seconds = 1 / 60
1057
+ end
1058
+
1059
+ return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
1060
+ local startTime = Promise._getTime()
1061
+ local endTime = startTime + seconds
1062
+
1063
+ local node = {
1064
+ resolve = resolve,
1065
+ startTime = startTime,
1066
+ endTime = endTime,
1067
+ }
1068
+
1069
+ if connection == nil then -- first is nil when connection is nil
1070
+ first = node
1071
+ connection = Promise._timeEvent:Connect(function()
1072
+ local threadStart = Promise._getTime()
1073
+
1074
+ while first ~= nil and first.endTime < threadStart do
1075
+ local current = first
1076
+ first = current.next
1077
+
1078
+ if first == nil then
1079
+ connection:Disconnect()
1080
+ connection = nil
1081
+ else
1082
+ first.previous = nil
1083
+ end
1084
+
1085
+ current.resolve(Promise._getTime() - current.startTime)
1086
+ end
1087
+ end)
1088
+ else -- first is non-nil
1089
+ if first.endTime < endTime then -- if `node` should be placed after `first`
1090
+ -- we will insert `node` between `current` and `next`
1091
+ -- (i.e. after `current` if `next` is nil)
1092
+ local current = first
1093
+ local next = current.next
1094
+
1095
+ while next ~= nil and next.endTime < endTime do
1096
+ current = next
1097
+ next = current.next
1098
+ end
1099
+
1100
+ -- `current` must be non-nil, but `next` could be `nil` (i.e. last item in list)
1101
+ current.next = node
1102
+ node.previous = current
1103
+
1104
+ if next ~= nil then
1105
+ node.next = next
1106
+ next.previous = node
1107
+ end
1108
+ else
1109
+ -- set `node` to `first`
1110
+ node.next = first
1111
+ first.previous = node
1112
+ first = node
1113
+ end
1114
+ end
1115
+
1116
+ onCancel(function()
1117
+ -- remove node from queue
1118
+ local next = node.next
1119
+
1120
+ if first == node then
1121
+ if next == nil then -- if `node` is the first and last
1122
+ connection:Disconnect()
1123
+ connection = nil
1124
+ else -- if `node` is `first` and not the last
1125
+ next.previous = nil
1126
+ end
1127
+ first = next
1128
+ else
1129
+ local previous = node.previous
1130
+ -- since `node` is not `first`, then we know `previous` is non-nil
1131
+ previous.next = next
1132
+
1133
+ if next ~= nil then
1134
+ next.previous = previous
1135
+ end
1136
+ end
1137
+ end)
1138
+ end)
1139
+ end
1140
+ end
1141
+
1142
+ --[=[
1143
+ Returns a new Promise that resolves if the chained Promise resolves within `seconds` seconds, or rejects if execution time exceeds `seconds`. The chained Promise will be cancelled if the timeout is reached.
1144
+
1145
+ Rejects with `rejectionValue` if it is non-nil. If a `rejectionValue` is not given, it will reject with a `Promise.Error(Promise.Error.Kind.TimedOut)`. This can be checked with [[Error.isKind]].
1146
+
1147
+ ```lua
1148
+ getSomething():timeout(5):andThen(function(something)
1149
+ -- got something and it only took at max 5 seconds
1150
+ end):catch(function(e)
1151
+ -- Either getting something failed or the time was exceeded.
1152
+
1153
+ if Promise.Error.isKind(e, Promise.Error.Kind.TimedOut) then
1154
+ warn("Operation timed out!")
1155
+ else
1156
+ warn("Operation encountered an error!")
1157
+ end
1158
+ end)
1159
+ ```
1160
+
1161
+ Sugar for:
1162
+
1163
+ ```lua
1164
+ Promise.race({
1165
+ Promise.delay(seconds):andThen(function()
1166
+ return Promise.reject(
1167
+ rejectionValue == nil
1168
+ and Promise.Error.new({ kind = Promise.Error.Kind.TimedOut })
1169
+ or rejectionValue
1170
+ )
1171
+ end),
1172
+ promise
1173
+ })
1174
+ ```
1175
+
1176
+ @param seconds number
1177
+ @param rejectionValue? any -- The value to reject with if the timeout is reached
1178
+ @return Promise
1179
+ ]=]
1180
+ function Promise.prototype:timeout(seconds, rejectionValue)
1181
+ local traceback = debug.traceback(nil, 2)
1182
+
1183
+ return Promise.race({
1184
+ Promise.delay(seconds):andThen(function()
1185
+ return Promise.reject(rejectionValue == nil and Error.new({
1186
+ kind = Error.Kind.TimedOut,
1187
+ error = "Timed out",
1188
+ context = string.format(
1189
+ "Timeout of %d seconds exceeded.\n:timeout() called at:\n\n%s",
1190
+ seconds,
1191
+ traceback
1192
+ ),
1193
+ }) or rejectionValue)
1194
+ end),
1195
+ self,
1196
+ })
1197
+ end
1198
+
1199
+ --[=[
1200
+ Returns the current Promise status.
1201
+
1202
+ @return Status
1203
+ ]=]
1204
+ function Promise.prototype:getStatus()
1205
+ return self._status
1206
+ end
1207
+
1208
+ --[[
1209
+ Creates a new promise that receives the result of this promise.
1210
+
1211
+ The given callbacks are invoked depending on that result.
1212
+ ]]
1213
+ function Promise.prototype:_andThen(traceback, successHandler, failureHandler)
1214
+ self._unhandledRejection = false
1215
+
1216
+ -- If we are already cancelled, we return a cancelled Promise
1217
+ if self._status == Promise.Status.Cancelled then
1218
+ local promise = Promise.new(function() end)
1219
+ promise:cancel()
1220
+
1221
+ return promise
1222
+ end
1223
+
1224
+ -- Create a new promise to follow this part of the chain
1225
+ return Promise._new(traceback, function(resolve, reject, onCancel)
1226
+ -- Our default callbacks just pass values onto the next promise.
1227
+ -- This lets success and failure cascade correctly!
1228
+
1229
+ local successCallback = resolve
1230
+ if successHandler then
1231
+ successCallback = createAdvancer(traceback, successHandler, resolve, reject)
1232
+ end
1233
+
1234
+ local failureCallback = reject
1235
+ if failureHandler then
1236
+ failureCallback = createAdvancer(traceback, failureHandler, resolve, reject)
1237
+ end
1238
+
1239
+ if self._status == Promise.Status.Started then
1240
+ -- If we haven't resolved yet, put ourselves into the queue
1241
+ table.insert(self._queuedResolve, successCallback)
1242
+ table.insert(self._queuedReject, failureCallback)
1243
+
1244
+ onCancel(function()
1245
+ -- These are guaranteed to exist because the cancellation handler is guaranteed to only
1246
+ -- be called at most once
1247
+ if self._status == Promise.Status.Started then
1248
+ table.remove(self._queuedResolve, table.find(self._queuedResolve, successCallback))
1249
+ table.remove(self._queuedReject, table.find(self._queuedReject, failureCallback))
1250
+ end
1251
+ end)
1252
+ elseif self._status == Promise.Status.Resolved then
1253
+ -- This promise has already resolved! Trigger success immediately.
1254
+ successCallback(unpack(self._values, 1, self._valuesLength))
1255
+ elseif self._status == Promise.Status.Rejected then
1256
+ -- This promise died a terrible death! Trigger failure immediately.
1257
+ failureCallback(unpack(self._values, 1, self._valuesLength))
1258
+ end
1259
+ end, self)
1260
+ end
1261
+
1262
+ --[=[
1263
+ Chains onto an existing Promise and returns a new Promise.
1264
+
1265
+ :::warning
1266
+ Within the failure handler, you should never assume that the rejection value is a string. Some rejections within the Promise library are represented by [[Error]] objects. If you want to treat it as a string for debugging, you should call `tostring` on it first.
1267
+ :::
1268
+
1269
+ You can return a Promise from the success or failure handler and it will be chained onto.
1270
+
1271
+ Calling `andThen` on a cancelled Promise returns a cancelled Promise.
1272
+
1273
+ :::tip
1274
+ If the Promise returned by `andThen` is cancelled, `successHandler` and `failureHandler` will not run.
1275
+
1276
+ To run code no matter what, use [Promise:finally].
1277
+ :::
1278
+
1279
+ @param successHandler (...: any) -> ...any
1280
+ @param failureHandler? (...: any) -> ...any
1281
+ @return Promise<...any>
1282
+ ]=]
1283
+ function Promise.prototype:andThen(successHandler, failureHandler)
1284
+ assert(successHandler == nil or isCallable(successHandler), string.format(ERROR_NON_FUNCTION, "Promise:andThen"))
1285
+ assert(failureHandler == nil or isCallable(failureHandler), string.format(ERROR_NON_FUNCTION, "Promise:andThen"))
1286
+
1287
+ return self:_andThen(debug.traceback(nil, 2), successHandler, failureHandler)
1288
+ end
1289
+
1290
+ --[=[
1291
+ Shorthand for `Promise:andThen(nil, failureHandler)`.
1292
+
1293
+ Returns a Promise that resolves if the `failureHandler` worked without encountering an additional error.
1294
+
1295
+ :::warning
1296
+ Within the failure handler, you should never assume that the rejection value is a string. Some rejections within the Promise library are represented by [[Error]] objects. If you want to treat it as a string for debugging, you should call `tostring` on it first.
1297
+ :::
1298
+
1299
+ Calling `catch` on a cancelled Promise returns a cancelled Promise.
1300
+
1301
+ :::tip
1302
+ If the Promise returned by `catch` is cancelled, `failureHandler` will not run.
1303
+
1304
+ To run code no matter what, use [Promise:finally].
1305
+ :::
1306
+
1307
+ @param failureHandler (...: any) -> ...any
1308
+ @return Promise<...any>
1309
+ ]=]
1310
+ function Promise.prototype:catch(failureHandler)
1311
+ assert(failureHandler == nil or isCallable(failureHandler), string.format(ERROR_NON_FUNCTION, "Promise:catch"))
1312
+ return self:_andThen(debug.traceback(nil, 2), nil, failureHandler)
1313
+ end
1314
+
1315
+ --[=[
1316
+ Similar to [Promise.andThen](#andThen), except the return value is the same as the value passed to the handler. In other words, you can insert a `:tap` into a Promise chain without affecting the value that downstream Promises receive.
1317
+
1318
+ ```lua
1319
+ getTheValue()
1320
+ :tap(print)
1321
+ :andThen(function(theValue)
1322
+ print("Got", theValue, "even though print returns nil!")
1323
+ end)
1324
+ ```
1325
+
1326
+ If you return a Promise from the tap handler callback, its value will be discarded but `tap` will still wait until it resolves before passing the original value through.
1327
+
1328
+ @param tapHandler (...: any) -> ...any
1329
+ @return Promise<...any>
1330
+ ]=]
1331
+ function Promise.prototype:tap(tapHandler)
1332
+ assert(isCallable(tapHandler), string.format(ERROR_NON_FUNCTION, "Promise:tap"))
1333
+ return self:_andThen(debug.traceback(nil, 2), function(...)
1334
+ local callbackReturn = tapHandler(...)
1335
+
1336
+ if Promise.is(callbackReturn) then
1337
+ local length, values = pack(...)
1338
+ return callbackReturn:andThen(function()
1339
+ return unpack(values, 1, length)
1340
+ end)
1341
+ end
1342
+
1343
+ return ...
1344
+ end)
1345
+ end
1346
+
1347
+ --[=[
1348
+ Attaches an `andThen` handler to this Promise that calls the given callback with the predefined arguments. The resolved value is discarded.
1349
+
1350
+ ```lua
1351
+ promise:andThenCall(someFunction, "some", "arguments")
1352
+ ```
1353
+
1354
+ This is sugar for
1355
+
1356
+ ```lua
1357
+ promise:andThen(function()
1358
+ return someFunction("some", "arguments")
1359
+ end)
1360
+ ```
1361
+
1362
+ @param callback (...: any) -> any
1363
+ @param ...? any -- Additional arguments which will be passed to `callback`
1364
+ @return Promise
1365
+ ]=]
1366
+ function Promise.prototype:andThenCall(callback, ...)
1367
+ assert(isCallable(callback), string.format(ERROR_NON_FUNCTION, "Promise:andThenCall"))
1368
+ local length, values = pack(...)
1369
+ return self:_andThen(debug.traceback(nil, 2), function()
1370
+ return callback(unpack(values, 1, length))
1371
+ end)
1372
+ end
1373
+
1374
+ --[=[
1375
+ Attaches an `andThen` handler to this Promise that discards the resolved value and returns the given value from it.
1376
+
1377
+ ```lua
1378
+ promise:andThenReturn("some", "values")
1379
+ ```
1380
+
1381
+ This is sugar for
1382
+
1383
+ ```lua
1384
+ promise:andThen(function()
1385
+ return "some", "values"
1386
+ end)
1387
+ ```
1388
+
1389
+ :::caution
1390
+ Promises are eager, so if you pass a Promise to `andThenReturn`, it will begin executing before `andThenReturn` is reached in the chain. Likewise, if you pass a Promise created from [[Promise.reject]] into `andThenReturn`, it's possible that this will trigger the unhandled rejection warning. If you need to return a Promise, it's usually best practice to use [[Promise.andThen]].
1391
+ :::
1392
+
1393
+ @param ... any -- Values to return from the function
1394
+ @return Promise
1395
+ ]=]
1396
+ function Promise.prototype:andThenReturn(...)
1397
+ local length, values = pack(...)
1398
+ return self:_andThen(debug.traceback(nil, 2), function()
1399
+ return unpack(values, 1, length)
1400
+ end)
1401
+ end
1402
+
1403
+ --[=[
1404
+ Cancels this promise, preventing the promise from resolving or rejecting. Does not do anything if the promise is already settled.
1405
+
1406
+ Cancellations will propagate upwards and downwards through chained promises.
1407
+
1408
+ Promises will only be cancelled if all of their consumers are also cancelled. This is to say that if you call `andThen` twice on the same promise, and you cancel only one of the child promises, it will not cancel the parent promise until the other child promise is also cancelled.
1409
+
1410
+ ```lua
1411
+ promise:cancel()
1412
+ ```
1413
+ ]=]
1414
+ function Promise.prototype:cancel()
1415
+ if self._status ~= Promise.Status.Started then
1416
+ return
1417
+ end
1418
+
1419
+ self._status = Promise.Status.Cancelled
1420
+
1421
+ if self._cancellationHook then
1422
+ self._cancellationHook()
1423
+ end
1424
+
1425
+ coroutine.close(self._thread)
1426
+
1427
+ if self._parent then
1428
+ self._parent:_consumerCancelled(self)
1429
+ end
1430
+
1431
+ for child in pairs(self._consumers) do
1432
+ child:cancel()
1433
+ end
1434
+
1435
+ self:_finalize()
1436
+ end
1437
+
1438
+ --[[
1439
+ Used to decrease the number of consumers by 1, and if there are no more,
1440
+ cancel this promise.
1441
+ ]]
1442
+ function Promise.prototype:_consumerCancelled(consumer)
1443
+ if self._status ~= Promise.Status.Started then
1444
+ return
1445
+ end
1446
+
1447
+ self._consumers[consumer] = nil
1448
+
1449
+ if next(self._consumers) == nil then
1450
+ self:cancel()
1451
+ end
1452
+ end
1453
+
1454
+ --[[
1455
+ Used to set a handler for when the promise resolves, rejects, or is
1456
+ cancelled.
1457
+ ]]
1458
+ function Promise.prototype:_finally(traceback, finallyHandler)
1459
+ self._unhandledRejection = false
1460
+
1461
+ local promise = Promise._new(traceback, function(resolve, reject, onCancel)
1462
+ local handlerPromise
1463
+
1464
+ onCancel(function()
1465
+ -- The finally Promise is not a proper consumer of self. We don't care about the resolved value.
1466
+ -- All we care about is running at the end. Therefore, if self has no other consumers, it's safe to
1467
+ -- cancel. We don't need to hold out cancelling just because there's a finally handler.
1468
+ self:_consumerCancelled(self)
1469
+
1470
+ if handlerPromise then
1471
+ handlerPromise:cancel()
1472
+ end
1473
+ end)
1474
+
1475
+ local finallyCallback = resolve
1476
+ if finallyHandler then
1477
+ finallyCallback = function(...)
1478
+ local callbackReturn = finallyHandler(...)
1479
+
1480
+ if Promise.is(callbackReturn) then
1481
+ handlerPromise = callbackReturn
1482
+
1483
+ callbackReturn
1484
+ :finally(function(status)
1485
+ if status ~= Promise.Status.Rejected then
1486
+ resolve(self)
1487
+ end
1488
+ end)
1489
+ :catch(function(...)
1490
+ reject(...)
1491
+ end)
1492
+ else
1493
+ resolve(self)
1494
+ end
1495
+ end
1496
+ end
1497
+
1498
+ if self._status == Promise.Status.Started then
1499
+ -- The promise is not settled, so queue this.
1500
+ table.insert(self._queuedFinally, finallyCallback)
1501
+ else
1502
+ -- The promise already settled or was cancelled, run the callback now.
1503
+ finallyCallback(self._status)
1504
+ end
1505
+ end)
1506
+
1507
+ return promise
1508
+ end
1509
+
1510
+ --[=[
1511
+ Set a handler that will be called regardless of the promise's fate. The handler is called when the promise is
1512
+ resolved, rejected, *or* cancelled.
1513
+
1514
+ Returns a new Promise that:
1515
+ - resolves with the same values that this Promise resolves with.
1516
+ - rejects with the same values that this Promise rejects with.
1517
+ - is cancelled if this Promise is cancelled.
1518
+
1519
+ If the value you return from the handler is a Promise:
1520
+ - We wait for the Promise to resolve, but we ultimately discard the resolved value.
1521
+ - If the returned Promise rejects, the Promise returned from `finally` will reject with the rejected value from the
1522
+ *returned* promise.
1523
+ - If the `finally` Promise is cancelled, and you returned a Promise from the handler, we cancel that Promise too.
1524
+
1525
+ Otherwise, the return value from the `finally` handler is entirely discarded.
1526
+
1527
+ :::note Cancellation
1528
+ As of Promise v4, `Promise:finally` does not count as a consumer of the parent Promise for cancellation purposes.
1529
+ This means that if all of a Promise's consumers are cancelled and the only remaining callbacks are finally handlers,
1530
+ the Promise is cancelled and the finally callbacks run then and there.
1531
+
1532
+ Cancellation still propagates through the `finally` Promise though: if you cancel the `finally` Promise, it can cancel
1533
+ its parent Promise if it had no other consumers. Likewise, if the parent Promise is cancelled, the `finally` Promise
1534
+ will also be cancelled.
1535
+ :::
1536
+
1537
+ ```lua
1538
+ local thing = createSomething()
1539
+
1540
+ doSomethingWith(thing)
1541
+ :andThen(function()
1542
+ print("It worked!")
1543
+ -- do something..
1544
+ end)
1545
+ :catch(function()
1546
+ warn("Oh no it failed!")
1547
+ end)
1548
+ :finally(function()
1549
+ -- either way, destroy thing
1550
+
1551
+ thing:Destroy()
1552
+ end)
1553
+
1554
+ ```
1555
+
1556
+ @param finallyHandler (status: Status) -> ...any
1557
+ @return Promise<...any>
1558
+ ]=]
1559
+ function Promise.prototype:finally(finallyHandler)
1560
+ assert(finallyHandler == nil or isCallable(finallyHandler), string.format(ERROR_NON_FUNCTION, "Promise:finally"))
1561
+ return self:_finally(debug.traceback(nil, 2), finallyHandler)
1562
+ end
1563
+
1564
+ --[=[
1565
+ Same as `andThenCall`, except for `finally`.
1566
+
1567
+ Attaches a `finally` handler to this Promise that calls the given callback with the predefined arguments.
1568
+
1569
+ @param callback (...: any) -> any
1570
+ @param ...? any -- Additional arguments which will be passed to `callback`
1571
+ @return Promise
1572
+ ]=]
1573
+ function Promise.prototype:finallyCall(callback, ...)
1574
+ assert(isCallable(callback), string.format(ERROR_NON_FUNCTION, "Promise:finallyCall"))
1575
+ local length, values = pack(...)
1576
+ return self:_finally(debug.traceback(nil, 2), function()
1577
+ return callback(unpack(values, 1, length))
1578
+ end)
1579
+ end
1580
+
1581
+ --[=[
1582
+ Attaches a `finally` handler to this Promise that discards the resolved value and returns the given value from it.
1583
+
1584
+ ```lua
1585
+ promise:finallyReturn("some", "values")
1586
+ ```
1587
+
1588
+ This is sugar for
1589
+
1590
+ ```lua
1591
+ promise:finally(function()
1592
+ return "some", "values"
1593
+ end)
1594
+ ```
1595
+
1596
+ @param ... any -- Values to return from the function
1597
+ @return Promise
1598
+ ]=]
1599
+ function Promise.prototype:finallyReturn(...)
1600
+ local length, values = pack(...)
1601
+ return self:_finally(debug.traceback(nil, 2), function()
1602
+ return unpack(values, 1, length)
1603
+ end)
1604
+ end
1605
+
1606
+ --[=[
1607
+ Yields the current thread until the given Promise completes. Returns the Promise's status, followed by the values that the promise resolved or rejected with.
1608
+
1609
+ @yields
1610
+ @return Status -- The Status representing the fate of the Promise
1611
+ @return ...any -- The values the Promise resolved or rejected with.
1612
+ ]=]
1613
+ function Promise.prototype:awaitStatus()
1614
+ self._unhandledRejection = false
1615
+
1616
+ if self._status == Promise.Status.Started then
1617
+ local thread = coroutine.running()
1618
+
1619
+ self
1620
+ :finally(function()
1621
+ task.spawn(thread)
1622
+ end)
1623
+ -- The finally promise can propagate rejections, so we attach a catch handler to prevent the unhandled
1624
+ -- rejection warning from appearing
1625
+ :catch(
1626
+ function() end
1627
+ )
1628
+
1629
+ coroutine.yield()
1630
+ end
1631
+
1632
+ if self._status == Promise.Status.Resolved then
1633
+ return self._status, unpack(self._values, 1, self._valuesLength)
1634
+ elseif self._status == Promise.Status.Rejected then
1635
+ return self._status, unpack(self._values, 1, self._valuesLength)
1636
+ end
1637
+
1638
+ return self._status
1639
+ end
1640
+
1641
+ local function awaitHelper(status, ...)
1642
+ return status == Promise.Status.Resolved, ...
1643
+ end
1644
+
1645
+ --[=[
1646
+ Yields the current thread until the given Promise completes. Returns true if the Promise resolved, followed by the values that the promise resolved or rejected with.
1647
+
1648
+ :::caution
1649
+ If the Promise gets cancelled, this function will return `false`, which is indistinguishable from a rejection. If you need to differentiate, you should use [[Promise.awaitStatus]] instead.
1650
+ :::
1651
+
1652
+ ```lua
1653
+ local worked, value = getTheValue():await()
1654
+
1655
+ if worked then
1656
+ print("got", value)
1657
+ else
1658
+ warn("it failed")
1659
+ end
1660
+ ```
1661
+
1662
+ @yields
1663
+ @return boolean -- `true` if the Promise successfully resolved
1664
+ @return ...any -- The values the Promise resolved or rejected with.
1665
+ ]=]
1666
+ function Promise.prototype:await()
1667
+ return awaitHelper(self:awaitStatus())
1668
+ end
1669
+
1670
+ local function expectHelper(status, ...)
1671
+ if status ~= Promise.Status.Resolved then
1672
+ error((...) == nil and "Expected Promise rejected with no value." or (...), 3)
1673
+ end
1674
+
1675
+ return ...
1676
+ end
1677
+
1678
+ --[=[
1679
+ Yields the current thread until the given Promise completes. Returns the values that the promise resolved with.
1680
+
1681
+ ```lua
1682
+ local worked = pcall(function()
1683
+ print("got", getTheValue():expect())
1684
+ end)
1685
+
1686
+ if not worked then
1687
+ warn("it failed")
1688
+ end
1689
+ ```
1690
+
1691
+ This is essentially sugar for:
1692
+
1693
+ ```lua
1694
+ select(2, assert(promise:await()))
1695
+ ```
1696
+
1697
+ **Errors** if the Promise rejects or gets cancelled.
1698
+
1699
+ @error any -- Errors with the rejection value if this Promise rejects or gets cancelled.
1700
+ @yields
1701
+ @return ...any -- The values the Promise resolved with.
1702
+ ]=]
1703
+ function Promise.prototype:expect()
1704
+ return expectHelper(self:awaitStatus())
1705
+ end
1706
+
1707
+ -- Backwards compatibility
1708
+ Promise.prototype.awaitValue = Promise.prototype.expect
1709
+
1710
+ --[[
1711
+ Intended for use in tests.
1712
+
1713
+ Similar to await(), but instead of yielding if the promise is unresolved,
1714
+ _unwrap will throw. This indicates an assumption that a promise has
1715
+ resolved.
1716
+ ]]
1717
+ function Promise.prototype:_unwrap()
1718
+ if self._status == Promise.Status.Started then
1719
+ error("Promise has not resolved or rejected.", 2)
1720
+ end
1721
+
1722
+ local success = self._status == Promise.Status.Resolved
1723
+
1724
+ return success, unpack(self._values, 1, self._valuesLength)
1725
+ end
1726
+
1727
+ function Promise.prototype:_resolve(...)
1728
+ if self._status ~= Promise.Status.Started then
1729
+ if Promise.is((...)) then
1730
+ (...):_consumerCancelled(self)
1731
+ end
1732
+ return
1733
+ end
1734
+
1735
+ -- If the resolved value was a Promise, we chain onto it!
1736
+ if Promise.is((...)) then
1737
+ -- Without this warning, arguments sometimes mysteriously disappear
1738
+ if select("#", ...) > 1 then
1739
+ local message = string.format(
1740
+ "When returning a Promise from andThen, extra arguments are " .. "discarded! See:\n\n%s",
1741
+ self._source
1742
+ )
1743
+ warn(message)
1744
+ end
1745
+
1746
+ local chainedPromise = ...
1747
+
1748
+ local promise = chainedPromise:andThen(function(...)
1749
+ self:_resolve(...)
1750
+ end, function(...)
1751
+ local maybeRuntimeError = chainedPromise._values[1]
1752
+
1753
+ -- Backwards compatibility < v2
1754
+ if chainedPromise._error then
1755
+ maybeRuntimeError = Error.new({
1756
+ error = chainedPromise._error,
1757
+ kind = Error.Kind.ExecutionError,
1758
+ context = "[No stack trace available as this Promise originated from an older version of the Promise library (< v2)]",
1759
+ })
1760
+ end
1761
+
1762
+ if Error.isKind(maybeRuntimeError, Error.Kind.ExecutionError) then
1763
+ return self:_reject(maybeRuntimeError:extend({
1764
+ error = "This Promise was chained to a Promise that errored.",
1765
+ trace = "",
1766
+ context = string.format(
1767
+ "The Promise at:\n\n%s\n...Rejected because it was chained to the following Promise, which encountered an error:\n",
1768
+ self._source
1769
+ ),
1770
+ }))
1771
+ end
1772
+
1773
+ self:_reject(...)
1774
+ end)
1775
+
1776
+ if promise._status == Promise.Status.Cancelled then
1777
+ self:cancel()
1778
+ elseif promise._status == Promise.Status.Started then
1779
+ -- Adopt ourselves into promise for cancellation propagation.
1780
+ self._parent = promise
1781
+ promise._consumers[self] = true
1782
+ end
1783
+
1784
+ return
1785
+ end
1786
+
1787
+ self._status = Promise.Status.Resolved
1788
+ self._valuesLength, self._values = pack(...)
1789
+
1790
+ -- We assume that these callbacks will not throw errors.
1791
+ for _, callback in ipairs(self._queuedResolve) do
1792
+ coroutine.wrap(callback)(...)
1793
+ end
1794
+
1795
+ self:_finalize()
1796
+ end
1797
+
1798
+ function Promise.prototype:_reject(...)
1799
+ if self._status ~= Promise.Status.Started then
1800
+ return
1801
+ end
1802
+
1803
+ self._status = Promise.Status.Rejected
1804
+ self._valuesLength, self._values = pack(...)
1805
+
1806
+ -- If there are any rejection handlers, call those!
1807
+ if not isEmpty(self._queuedReject) then
1808
+ -- We assume that these callbacks will not throw errors.
1809
+ for _, callback in ipairs(self._queuedReject) do
1810
+ coroutine.wrap(callback)(...)
1811
+ end
1812
+ else
1813
+ -- At this point, no one was able to observe the error.
1814
+ -- An error handler might still be attached if the error occurred
1815
+ -- synchronously. We'll wait one tick, and if there are still no
1816
+ -- observers, then we should put a message in the console.
1817
+
1818
+ local err = tostring((...))
1819
+
1820
+ coroutine.wrap(function()
1821
+ Promise._timeEvent:Wait()
1822
+
1823
+ -- Someone observed the error, hooray!
1824
+ if not self._unhandledRejection then
1825
+ return
1826
+ end
1827
+
1828
+ -- Build a reasonable message
1829
+ local message = string.format("Unhandled Promise rejection:\n\n%s\n\n%s", err, self._source)
1830
+
1831
+ for _, callback in ipairs(Promise._unhandledRejectionCallbacks) do
1832
+ task.spawn(callback, self, unpack(self._values, 1, self._valuesLength))
1833
+ end
1834
+
1835
+ if Promise.TEST then
1836
+ -- Don't spam output when we're running tests.
1837
+ return
1838
+ end
1839
+
1840
+ warn(message)
1841
+ end)()
1842
+ end
1843
+
1844
+ self:_finalize()
1845
+ end
1846
+
1847
+ --[[
1848
+ Calls any :finally handlers. We need this to be a separate method and
1849
+ queue because we must call all of the finally callbacks upon a success,
1850
+ failure, *and* cancellation.
1851
+ ]]
1852
+ function Promise.prototype:_finalize()
1853
+ for _, callback in ipairs(self._queuedFinally) do
1854
+ -- Purposefully not passing values to callbacks here, as it could be the
1855
+ -- resolved values, or rejected errors. If the developer needs the values,
1856
+ -- they should use :andThen or :catch explicitly.
1857
+ coroutine.wrap(callback)(self._status)
1858
+ end
1859
+
1860
+ self._queuedFinally = nil
1861
+ self._queuedReject = nil
1862
+ self._queuedResolve = nil
1863
+
1864
+ -- Clear references to other Promises to allow gc
1865
+ if not Promise.TEST then
1866
+ self._parent = nil
1867
+ self._consumers = nil
1868
+ end
1869
+
1870
+ task.defer(coroutine.close, self._thread)
1871
+ end
1872
+
1873
+ --[=[
1874
+ Chains a Promise from this one that is resolved if this Promise is already resolved, and rejected if it is not resolved at the time of calling `:now()`. This can be used to ensure your `andThen` handler occurs on the same frame as the root Promise execution.
1875
+
1876
+ ```lua
1877
+ doSomething()
1878
+ :now()
1879
+ :andThen(function(value)
1880
+ print("Got", value, "synchronously.")
1881
+ end)
1882
+ ```
1883
+
1884
+ If this Promise is still running, Rejected, or Cancelled, the Promise returned from `:now()` will reject with the `rejectionValue` if passed, otherwise with a `Promise.Error(Promise.Error.Kind.NotResolvedInTime)`. This can be checked with [[Error.isKind]].
1885
+
1886
+ @param rejectionValue? any -- The value to reject with if the Promise isn't resolved
1887
+ @return Promise
1888
+ ]=]
1889
+ function Promise.prototype:now(rejectionValue)
1890
+ local traceback = debug.traceback(nil, 2)
1891
+ if self._status == Promise.Status.Resolved then
1892
+ return self:_andThen(traceback, function(...)
1893
+ return ...
1894
+ end)
1895
+ else
1896
+ return Promise.reject(rejectionValue == nil and Error.new({
1897
+ kind = Error.Kind.NotResolvedInTime,
1898
+ error = "This Promise was not resolved in time for :now()",
1899
+ context = ":now() was called at:\n\n" .. traceback,
1900
+ }) or rejectionValue)
1901
+ end
1902
+ end
1903
+
1904
+ --[=[
1905
+ Repeatedly calls a Promise-returning function up to `times` number of times, until the returned Promise resolves.
1906
+
1907
+ If the amount of retries is exceeded, the function will return the latest rejected Promise.
1908
+
1909
+ ```lua
1910
+ local function canFail(a, b, c)
1911
+ return Promise.new(function(resolve, reject)
1912
+ -- do something that can fail
1913
+
1914
+ local failed, thing = doSomethingThatCanFail(a, b, c)
1915
+
1916
+ if failed then
1917
+ reject("it failed")
1918
+ else
1919
+ resolve(thing)
1920
+ end
1921
+ end)
1922
+ end
1923
+
1924
+ local MAX_RETRIES = 10
1925
+ local value = Promise.retry(canFail, MAX_RETRIES, "foo", "bar", "baz") -- args to send to canFail
1926
+ ```
1927
+
1928
+ @since 3.0.0
1929
+ @param callback (...: P) -> Promise<T>
1930
+ @param times number
1931
+ @param ...? P
1932
+ @return Promise<T>
1933
+ ]=]
1934
+ function Promise.retry(callback, times, ...)
1935
+ assert(isCallable(callback), "Parameter #1 to Promise.retry must be a function")
1936
+ assert(type(times) == "number", "Parameter #2 to Promise.retry must be a number")
1937
+
1938
+ local args, length = { ... }, select("#", ...)
1939
+
1940
+ return Promise.resolve(callback(...)):catch(function(...)
1941
+ if times > 0 then
1942
+ return Promise.retry(callback, times - 1, unpack(args, 1, length))
1943
+ else
1944
+ return Promise.reject(...)
1945
+ end
1946
+ end)
1947
+ end
1948
+
1949
+ --[=[
1950
+ Repeatedly calls a Promise-returning function up to `times` number of times, waiting `seconds` seconds between each
1951
+ retry, until the returned Promise resolves.
1952
+
1953
+ If the amount of retries is exceeded, the function will return the latest rejected Promise.
1954
+
1955
+ @since v3.2.0
1956
+ @param callback (...: P) -> Promise<T>
1957
+ @param times number
1958
+ @param seconds number
1959
+ @param ...? P
1960
+ @return Promise<T>
1961
+ ]=]
1962
+ function Promise.retryWithDelay(callback, times, seconds, ...)
1963
+ assert(isCallable(callback), "Parameter #1 to Promise.retry must be a function")
1964
+ assert(type(times) == "number", "Parameter #2 (times) to Promise.retry must be a number")
1965
+ assert(type(seconds) == "number", "Parameter #3 (seconds) to Promise.retry must be a number")
1966
+
1967
+ local args, length = { ... }, select("#", ...)
1968
+
1969
+ return Promise.resolve(callback(...)):catch(function(...)
1970
+ if times > 0 then
1971
+ Promise.delay(seconds):await()
1972
+
1973
+ return Promise.retryWithDelay(callback, times - 1, seconds, unpack(args, 1, length))
1974
+ else
1975
+ return Promise.reject(...)
1976
+ end
1977
+ end)
1978
+ end
1979
+
1980
+ --[=[
1981
+ Converts an event into a Promise which resolves the next time the event fires.
1982
+
1983
+ The optional `predicate` callback, if passed, will receive the event arguments and should return `true` or `false`, based on if this fired event should resolve the Promise or not. If `true`, the Promise resolves. If `false`, nothing happens and the predicate will be rerun the next time the event fires.
1984
+
1985
+ The Promise will resolve with the event arguments.
1986
+
1987
+ :::tip
1988
+ This function will work given any object with a `Connect` method. This includes all Roblox events.
1989
+ :::
1990
+
1991
+ ```lua
1992
+ -- Creates a Promise which only resolves when `somePart` is touched
1993
+ -- by a part named `"Something specific"`.
1994
+ return Promise.fromEvent(somePart.Touched, function(part)
1995
+ return part.Name == "Something specific"
1996
+ end)
1997
+ ```
1998
+
1999
+ @since 3.0.0
2000
+ @param event Event -- Any object with a `Connect` method. This includes all Roblox events.
2001
+ @param predicate? (...: P) -> boolean -- A function which determines if the Promise should resolve with the given value, or wait for the next event to check again.
2002
+ @return Promise<P>
2003
+ ]=]
2004
+ function Promise.fromEvent(event, predicate)
2005
+ predicate = predicate or function()
2006
+ return true
2007
+ end
2008
+
2009
+ return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
2010
+ local connection
2011
+ local shouldDisconnect = false
2012
+
2013
+ local function disconnect()
2014
+ connection:Disconnect()
2015
+ connection = nil
2016
+ end
2017
+
2018
+ -- We use shouldDisconnect because if the callback given to Connect is called before
2019
+ -- Connect returns, connection will still be nil. This happens with events that queue up
2020
+ -- events when there's nothing connected, such as RemoteEvents
2021
+
2022
+ connection = event:Connect(function(...)
2023
+ local callbackValue = predicate(...)
2024
+
2025
+ if callbackValue == true then
2026
+ resolve(...)
2027
+
2028
+ if connection then
2029
+ disconnect()
2030
+ else
2031
+ shouldDisconnect = true
2032
+ end
2033
+ elseif type(callbackValue) ~= "boolean" then
2034
+ error("Promise.fromEvent predicate should always return a boolean")
2035
+ end
2036
+ end)
2037
+
2038
+ if shouldDisconnect and connection then
2039
+ return disconnect()
2040
+ end
2041
+
2042
+ onCancel(disconnect)
2043
+ end)
2044
+ end
2045
+
2046
+ --[=[
2047
+ Registers a callback that runs when an unhandled rejection happens. An unhandled rejection happens when a Promise
2048
+ is rejected, and the rejection is not observed with `:catch`.
2049
+
2050
+ The callback is called with the actual promise that rejected, followed by the rejection values.
2051
+
2052
+ @since v3.2.0
2053
+ @param callback (promise: Promise, ...: any) -- A callback that runs when an unhandled rejection happens.
2054
+ @return () -> () -- Function that unregisters the `callback` when called
2055
+ ]=]
2056
+ function Promise.onUnhandledRejection(callback)
2057
+ table.insert(Promise._unhandledRejectionCallbacks, callback)
2058
+
2059
+ return function()
2060
+ local index = table.find(Promise._unhandledRejectionCallbacks, callback)
2061
+
2062
+ if index then
2063
+ table.remove(Promise._unhandledRejectionCallbacks, index)
2064
+ end
2065
+ end
2066
+ end
2067
+
2068
+ return Promise