codeceptjs 4.2.2 → 4.2.4

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 (74) hide show
  1. package/README.md +4 -4
  2. package/docs/ai.md +1 -1
  3. package/docs/alternative-browsers.md +4 -4
  4. package/docs/api.md +13 -13
  5. package/docs/assertions.md +6 -6
  6. package/docs/best.md +1 -1
  7. package/docs/bootstrap.md +1 -1
  8. package/docs/data.md +8 -8
  9. package/docs/element-selection.md +27 -4
  10. package/docs/helpers/ApiDataFactory.md +2 -2
  11. package/docs/helpers/Appium.md +56 -56
  12. package/docs/helpers/Decision.md +1 -1
  13. package/docs/helpers/Detox.md +1 -1
  14. package/docs/helpers/ExpectHelper.md +1 -1
  15. package/docs/helpers/FileSystem.md +1 -1
  16. package/docs/helpers/GraphQL.md +1 -1
  17. package/docs/helpers/GraphQLDataFactory.md +2 -2
  18. package/docs/helpers/JSONResponse.md +1 -1
  19. package/docs/helpers/Kitesurf.md +65 -65
  20. package/docs/helpers/Lightpanda.md +65 -65
  21. package/docs/helpers/MockRequest.md +1 -1
  22. package/docs/helpers/Moli.md +65 -65
  23. package/docs/helpers/Obscura.md +65 -65
  24. package/docs/helpers/Playwright.md +127 -127
  25. package/docs/helpers/Puppeteer.md +88 -88
  26. package/docs/helpers/REST.md +1 -1
  27. package/docs/helpers/WebDriver.md +87 -87
  28. package/docs/installation.md +1 -1
  29. package/docs/locators.md +5 -7
  30. package/docs/migration-4.md +7 -3
  31. package/docs/mobile.md +2 -2
  32. package/docs/parallel.md +1 -1
  33. package/docs/playwright.md +5 -5
  34. package/docs/plugins/aiTrace.md +1 -1
  35. package/docs/plugins/autoDelay.md +1 -1
  36. package/docs/plugins/customLocator.md +1 -1
  37. package/docs/plugins/customReporter.md +1 -1
  38. package/docs/plugins/junitReporter.md +2 -2
  39. package/docs/plugins/pageInfo.md +1 -1
  40. package/docs/plugins/pauseOnFail.md +1 -1
  41. package/docs/plugins/retryFailedStep.md +1 -1
  42. package/docs/plugins/screenshotOnFail.md +1 -1
  43. package/docs/plugins/stepTimeout.md +1 -1
  44. package/docs/plugins.md +10 -10
  45. package/docs/puppeteer.md +4 -4
  46. package/docs/retry.md +1 -1
  47. package/docs/timeouts.md +7 -7
  48. package/docs/webdriver.md +8 -8
  49. package/lib/actor.js +20 -2
  50. package/lib/aria.js +1 -0
  51. package/lib/codecept.js +1 -1
  52. package/lib/data/context.js +24 -0
  53. package/lib/element/WebElement.js +5 -5
  54. package/lib/helper/ApiDataFactory.js +1 -1
  55. package/lib/helper/Appium.js +2 -2
  56. package/lib/helper/GraphQLDataFactory.js +1 -1
  57. package/lib/helper/Playwright.js +22 -12
  58. package/lib/helper/Puppeteer.js +5 -11
  59. package/lib/mocha/asyncWrapper.js +14 -3
  60. package/lib/mocha/test.js +1 -0
  61. package/lib/plugin/auth.js +3 -0
  62. package/lib/plugin/junitReporter.js +21 -12
  63. package/lib/recorder.js +22 -3
  64. package/lib/step/base.js +8 -1
  65. package/lib/step/func.js +1 -1
  66. package/lib/step/helper.js +1 -1
  67. package/lib/step/record.js +22 -17
  68. package/lib/step/retry.js +13 -6
  69. package/lib/utils/typescript.js +86 -12
  70. package/lib/workers.js +15 -0
  71. package/package.json +2 -1
  72. package/typings/index.d.ts +12 -0
  73. package/typings/promiseBasedTypes.d.ts +696 -351
  74. package/typings/types.d.ts +485 -352
@@ -554,9 +554,10 @@ class Playwright extends Helper {
554
554
  return
555
555
  }
556
556
 
557
- // Start browser if not manually started and not already running
558
- // Browser should start in singleton mode (restart: false) or when restart strategy is enabled
559
- if (!this.options.manualStart && !this.isRunning) {
557
+ // Start browser if not manually started and not already running.
558
+ // With the browser restart strategy, _before() starts a browser for each test,
559
+ // and a browser started here would never be closed (#5784)
560
+ if (!this.options.manualStart && !this.isRunning && !restartsBrowser()) {
560
561
  this.debugSection('Session', 'Starting singleton browser session')
561
562
  return this._startBrowser()
562
563
  }
@@ -2054,7 +2055,7 @@ class Playwright extends Helper {
2054
2055
  * Handles a file download. A file name is required to save the file on disk.
2055
2056
  * Files are saved to "output" directory.
2056
2057
  *
2057
- * Should be used with [FileSystem helper](https://codecept.io/helpers/FileSystem) to check that file were downloaded correctly.
2058
+ * Should be used with [FileSystem helper](https://codecept.io/helpers/file-system) to check that file were downloaded correctly.
2058
2059
  *
2059
2060
  * ```js
2060
2061
  * I.handleDownloads('downloads/avatar.jpg');
@@ -2140,7 +2141,7 @@ class Playwright extends Helper {
2140
2141
  * @param {CodeceptJS.LocatorOrString|number} locator Element to click on or X coordinate if no element.
2141
2142
  * @param {number} [x] X coordinate relative to element, or Y coordinate if locator is a number.
2142
2143
  * @param {number} [y] Y coordinate relative to element.
2143
- * @returns {Promise<void>}
2144
+ * @returns {CodeceptJS.ElementStepPromise}
2144
2145
  */
2145
2146
  async clickXY(locator, x, y) {
2146
2147
  // If locator is a number, treat it as global X coordinate
@@ -3565,6 +3566,8 @@ class Playwright extends Helper {
3565
3566
 
3566
3567
  /**
3567
3568
  * {{> waitForText }}
3569
+ *
3570
+ * . **Note:** Text matching is case-sensitive. For case-insensitive matching, use XPath or CSS locators with normalized text.
3568
3571
  */
3569
3572
  async waitForText(text, sec = null, context = null) {
3570
3573
  const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
@@ -3576,13 +3579,20 @@ class Playwright extends Helper {
3576
3579
  const locator = new Locator(context, 'css')
3577
3580
  try {
3578
3581
  if (!locator.isXPath()) {
3579
- return contextObject
3580
- .locator(`${locator.simplify()} >> text=${text}`)
3581
- .first()
3582
- .waitFor({ timeout: waitTimeout, state: 'visible' })
3583
- .catch(e => {
3584
- throw new Error(errorMessage)
3585
- })
3582
+ try {
3583
+ const deadline = Date.now() + waitTimeout
3584
+ do {
3585
+ const els = await this._locate(locator)
3586
+ for (const el of els) {
3587
+ const texts = await el.evaluateAll(nodes => nodes.map(node => node.innerText ?? node.textContent))
3588
+ if (texts.some(t => typeof t === 'string' && t.includes(text))) return
3589
+ }
3590
+ await new Promise(resolve => setTimeout(resolve, 100))
3591
+ } while (Date.now() < deadline)
3592
+ throw new Error(errorMessage)
3593
+ } catch (e) {
3594
+ throw new Error(errorMessage)
3595
+ }
3586
3596
  }
3587
3597
 
3588
3598
  if (locator.isXPath()) {
@@ -94,7 +94,7 @@ const consoleLogStore = new Console()
94
94
  * @prop {string} [windowSize] - default window size. Set a dimension in format WIDTHxHEIGHT like `640x480`.
95
95
  * @prop {string} [userAgent] - user-agent string.
96
96
  * @prop {boolean} [manualStart=false] - do not start browser before a test, start it manually inside a helper with `this.helpers["Puppeteer"]._startBrowser()`.
97
- * @prop {string} [browser=chrome] - can be changed to `firefox` when using [puppeteer-firefox](https://codecept.io/helpers/Puppeteer-firefox).
97
+ * @prop {string} [browser=chrome] - can be changed to `firefox` when using [puppeteer-firefox](https://codecept.io/helpers/puppeteer-firefox).
98
98
  * @prop {object} [chrome] - pass additional [Puppeteer run options](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.launchoptions.md).
99
99
  * @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose).
100
100
  */
@@ -115,7 +115,7 @@ const config = {}
115
115
  * ```
116
116
  * Using `puppeteer-core` package, will prevent the download of browser binaries and allow connecting to an existing browser installation or for connecting to a remote one.
117
117
  *
118
- * > Experimental Firefox support [can be activated](https://codecept.io/helpers/Puppeteer-firefox).
118
+ * > Experimental Firefox support [can be activated](https://codecept.io/helpers/puppeteer-firefox).
119
119
  *
120
120
  * <!-- configuration -->
121
121
  *
@@ -1097,12 +1097,6 @@ class Puppeteer extends Helper {
1097
1097
  return new WebElement(elements[0], this)
1098
1098
  }
1099
1099
 
1100
- async grabWebElement(locator) {
1101
- const els = await this._locate(locator)
1102
- assertElementExists(els, locator)
1103
- return els[0]
1104
- }
1105
-
1106
1100
  /**
1107
1101
  * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1108
1102
  *
@@ -1299,7 +1293,7 @@ class Puppeteer extends Helper {
1299
1293
  } else {
1300
1294
  assertElementExists(els, locator, 'Clickable element')
1301
1295
  }
1302
- const elem = els[0]
1296
+ const elem = selectElement(els, locator, this)
1303
1297
  return this.executeScript(el => {
1304
1298
  if (document.activeElement instanceof HTMLElement) {
1305
1299
  document.activeElement.blur()
@@ -1320,7 +1314,7 @@ class Puppeteer extends Helper {
1320
1314
 
1321
1315
  /**
1322
1316
  * Sets a directory to where save files. Allows to test file downloads.
1323
- * Should be used with [FileSystem helper](https://codecept.io/helpers/FileSystem) to check that file were downloaded correctly.
1317
+ * Should be used with [FileSystem helper](https://codecept.io/helpers/file-system) to check that file were downloaded correctly.
1324
1318
  *
1325
1319
  * By default, files are saved to `output/downloads`.
1326
1320
  * This directory is cleaned on every `handleDownloads` call, to ensure no old files are kept.
@@ -2271,7 +2265,7 @@ class Puppeteer extends Helper {
2271
2265
  const els = await this._locate(locator)
2272
2266
  const array = []
2273
2267
  for (let index = 0; index < els.length; index++) {
2274
- const a = await this._evaluateHandeInContext((el, attr) => el[attr] || el.getAttribute(attr), els[index], attr)
2268
+ const a = await this._evaluateHandeInContext((el, attr) => (attr === 'style' ? el.getAttribute(attr) : el[attr] || el.getAttribute(attr)), els[index], attr)
2275
2269
  array.push(a)
2276
2270
  }
2277
2271
  return array
@@ -54,7 +54,10 @@ export function test(test) {
54
54
 
55
55
  test.fn = function (done) {
56
56
  const doneFn = makeDoneCallableOnce(done)
57
+ let recoveryStarted = false
57
58
  recorder.errHandler(err => {
59
+ if (recoveryStarted) return
60
+ recoveryStarted = true
58
61
  recorder.session.start('teardown')
59
62
  recorder.cleanAsyncErr()
60
63
  if (test.throws) {
@@ -114,7 +117,13 @@ export function test(test) {
114
117
  export function injected(fn, suite, hookName) {
115
118
  return function (done) {
116
119
  const doneFn = makeDoneCallableOnce(done)
120
+ const opts = suite.opts || {}
121
+ const retries = opts[`retry${ucfirst(hookName)}`] || 0
122
+ let retryPending = retries > 0
123
+ let recoveryStarted = false
117
124
  const errHandler = err => {
125
+ if (retryPending || recoveryStarted) return
126
+ recoveryStarted = true
118
127
  recorder.session.start('teardown')
119
128
  recorder.cleanAsyncErr()
120
129
  if (['before', 'beforeSuite'].includes(hookName)) {
@@ -149,9 +158,6 @@ export function injected(fn, suite, hookName) {
149
158
  })
150
159
  }
151
160
 
152
- const opts = suite.opts || {}
153
- const retries = opts[`retry${ucfirst(hookName)}`] || 0
154
-
155
161
  const currentTest = hookName === 'before' || hookName === 'after' ? suite?.ctx?.currentTest : null
156
162
 
157
163
  promiseRetry(
@@ -165,8 +171,13 @@ export function injected(fn, suite, hookName) {
165
171
  retry(err)
166
172
  } finally {
167
173
  if (number < retries) {
174
+ // drain the failed chain so in-flight steps (sessions, listeners)
175
+ // finish before the next attempt starts queueing new ones
176
+ await recorder.promise().catch(() => {})
168
177
  recorder.stop()
169
178
  recorder.start()
179
+ } else {
180
+ retryPending = false
170
181
  }
171
182
  }
172
183
  },
package/lib/mocha/test.js CHANGED
@@ -106,6 +106,7 @@ function serializeTest(test, error = null) {
106
106
  const parent = {}
107
107
  if (test.parent) {
108
108
  parent.title = test.parent.title
109
+ parent.file = test.parent.file
109
110
  }
110
111
 
111
112
  if (test.opts) {
@@ -303,6 +303,7 @@ export default function (config) {
303
303
 
304
304
  section.start()
305
305
 
306
+ const queueId = recorder.getQueueId()
306
307
  const cookies = store[`${name}_session`]
307
308
  const shouldAwait = isAsyncFunction(userSession.login) || isAsyncFunction(userSession.restore) || isAsyncFunction(userSession.check)
308
309
 
@@ -338,6 +339,7 @@ export default function (config) {
338
339
  }
339
340
  section.end()
340
341
  recorder.session.catch(err => {
342
+ if (recorder.getQueueId() !== queueId) return
341
343
  output.debug(`Failed auto login for ${name} due to ${err}`)
342
344
  output.debug('Logging in again')
343
345
  recorder.session.start('auto login')
@@ -355,6 +357,7 @@ export default function (config) {
355
357
  })
356
358
  })
357
359
  recorder.add(() => {
360
+ if (recorder.getQueueId() !== queueId) return
358
361
  recorder.session.restore('check login')
359
362
  })
360
363
 
@@ -1,6 +1,7 @@
1
1
  import fs from 'fs'
2
2
  import path from 'path'
3
3
  import os from 'os'
4
+ import { isMainThread } from 'worker_threads'
4
5
  import { mkdirp } from 'mkdirp'
5
6
  import { DOMImplementation, XMLSerializer } from '@xmldom/xmldom'
6
7
 
@@ -45,7 +46,7 @@ const INVALID_XML_CHARS = new RegExp('[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u0
45
46
  * Possible config options:
46
47
  *
47
48
  * * `outputName`: file name for the report. Default: `report.xml`.
48
- * * `output`: directory where the report is stored, relative to the project root. Default: the `output` directory.
49
+ * * `output`: directory where the report is stored, relative to the project root. Default: the `output` directory. With `run-workers` and `multiple` runs, each run writes its own report into its run folder (e.g. `output/dev_chromium1`) and this option is ignored.
49
50
  * * `testGroupName`: value of the `name` attribute on the root `<testsuites>` element. Default: `CodeceptJS`.
50
51
  * * `attachMeta`: add the test's meta information (`meta` keys, `tags`, `retries`) as `<properties>`. Default: true.
51
52
  * * `attachSteps`: add the step/substep log as `<system-out>`. Default: true.
@@ -67,10 +68,6 @@ export default function (config = {}) {
67
68
 
68
69
  let written = false
69
70
  const hookFailures = []
70
- // groupBySuite() (below) groups by object identity, not by value — reused
71
- // across BeforeSuite/AfterSuite failures from the same worker-forwarded
72
- // suite so they land in one <testsuite>, not one per failure.
73
- const workerSuiteByKey = new Map()
74
71
 
75
72
  event.dispatcher.on(event.hook.failed, hook => {
76
73
  if (!hook || !['BeforeSuite', 'AfterSuite'].includes(hook.hookName)) return
@@ -84,11 +81,7 @@ export default function (config = {}) {
84
81
  // groups under its real suite instead of the "Tests" fallback.
85
82
  let suite = runnable && runnable.parent
86
83
  if (!suite && hook.suiteTitle) {
87
- const key = `${hook.suiteTitle} ${hook.suiteFile || ''}`
88
- if (!workerSuiteByKey.has(key)) {
89
- workerSuiteByKey.set(key, { title: hook.suiteTitle, file: hook.suiteFile, tags: hook.suiteTags })
90
- }
91
- suite = workerSuiteByKey.get(key)
84
+ suite = { title: hook.suiteTitle, file: hook.suiteFile, tags: hook.suiteTags }
92
85
  }
93
86
  hookFailures.push({
94
87
  title: hook.title || `${hook.hookName} hook failed`,
@@ -100,19 +93,35 @@ export default function (config = {}) {
100
93
  meta: {},
101
94
  steps: [],
102
95
  duration: (runnable && runnable.duration) || 0,
96
+ outputDir: hook.outputDir,
103
97
  })
104
98
  })
105
99
 
106
100
  const writeReport = result => {
107
101
  if (written) return
108
102
  if (!result || !Array.isArray(result.tests)) return
103
+ if (!isMainThread) return
109
104
  written = true
110
105
 
106
+ const runDirs = [...new Set(result.tests.map(test => test.outputDir).filter(Boolean))]
107
+ if (runDirs.length) {
108
+ for (const dir of runDirs) {
109
+ const runResult = { tests: result.tests.filter(test => test.outputDir === dir), stats: result.stats }
110
+ const runHookFailures = hookFailures.filter(hf => hf.outputDir === dir)
111
+ saveXml(dir, buildXml(runResult, config, runHookFailures))
112
+ }
113
+ return
114
+ }
115
+
111
116
  const dir = config.output ? path.resolve(store.codeceptDir || process.cwd(), config.output) : store.outputDir || process.cwd()
117
+ saveXml(dir, buildXml(result, config, hookFailures))
118
+ }
119
+
120
+ const saveXml = (dir, xml) => {
112
121
  mkdirp.sync(dir)
113
122
  const file = path.join(dir, config.outputName)
114
123
 
115
- fs.writeFileSync(file, buildXml(result, config, hookFailures))
124
+ fs.writeFileSync(file, xml)
116
125
  output.plugin('junitReporter', `JUnit report saved to ${file}`)
117
126
  }
118
127
 
@@ -296,7 +305,7 @@ function groupBySuite(tests) {
296
305
  const groups = []
297
306
  const byKey = new Map()
298
307
  for (const test of tests) {
299
- const key = test.parent || test
308
+ const key = test.parent ? `${test.parent.title}\0${test.parent.file || test.file || ''}` : test
300
309
  if (!byKey.has(key)) {
301
310
  const list = []
302
311
  byKey.set(key, list)
package/lib/recorder.js CHANGED
@@ -89,6 +89,8 @@ export default {
89
89
  */
90
90
  reset() {
91
91
  if (promise && running) this.catch()
92
+ else swallow(promise)
93
+ oldPromises.forEach(swallow)
92
94
  queueId++
93
95
  sessionId = null
94
96
  sessionStack = [] // Clear the session stack
@@ -125,6 +127,16 @@ export default {
125
127
  * @inner
126
128
  */
127
129
  start(name) {
130
+ if (sessionId === name) {
131
+ // re-starting the same session abandons the current (broken) chain
132
+ // without polluting the session stack
133
+ debug(`${currentQueue()}Session <${name}> already started, abandoning its chain`)
134
+ tasks.push('--->')
135
+ this.running = true
136
+ swallow(promise)
137
+ promise = Promise.resolve()
138
+ return
139
+ }
128
140
  if (sessionId) {
129
141
  debug(`${currentQueue()}Session already started as ${sessionId}, nesting session ${name}`)
130
142
  // Push current session to stack instead of restoring it
@@ -136,7 +148,7 @@ export default {
136
148
  }
137
149
  debug(`${currentQueue()}Starting <${name}> session`)
138
150
  tasks.push('--->')
139
- oldPromises.push(promise)
151
+ oldPromises.push(swallow(promise))
140
152
  this.running = true
141
153
  sessionId = name
142
154
  promise = Promise.resolve()
@@ -151,7 +163,8 @@ export default {
151
163
  debug(`${currentQueue()}Finalize <${name}> session`)
152
164
  this.running = false
153
165
  this.catch(errFn)
154
- promise = promise.then(() => oldPromises.pop())
166
+ const restored = oldPromises.pop()
167
+ if (restored && restored !== promise) promise = promise.then(() => restored)
155
168
 
156
169
  // Restore parent session from stack if available
157
170
  if (sessionStack.length > 0) {
@@ -184,7 +197,7 @@ export default {
184
197
  * undefined: `add(fn)` -> `false` and `add('step',fn)` -> `true`
185
198
  * true: it will retries if `retryOpts` set.
186
199
  * false: ignore `retryOpts` and won't retry.
187
- * @param {number} [timeout]
200
+ * @param {number|function} [timeout] in milliseconds, or a function returning it when the task starts
188
201
  * @return {Promise<*>}
189
202
  * @inner
190
203
  */
@@ -202,6 +215,7 @@ export default {
202
215
  debug(chalk.gray(`${currentQueue()} Queued | ${taskName}`))
203
216
 
204
217
  return (promise = Promise.resolve(promise).then(res => {
218
+ if (typeof timeout === 'function') timeout = timeout()
205
219
  debug(`${currentQueue()} Running | ${taskName} | Timeout: ${timeout || 'None'}`)
206
220
 
207
221
  const runTask = () => {
@@ -426,6 +440,11 @@ export default {
426
440
  },
427
441
  }
428
442
 
443
+ function swallow(p) {
444
+ if (p) p.catch(() => {})
445
+ return p
446
+ }
447
+
429
448
  function getTimeoutPromise(timeoutMs, taskName) {
430
449
  let timer
431
450
  if (timeoutMs) debug(`Timing out in ${timeoutMs}ms`)
package/lib/step/base.js CHANGED
@@ -5,6 +5,7 @@ import { getCurrentTimeout } from '../timeout.js'
5
5
  import { ucfirst, humanizeString, serializeError } from '../utils.js'
6
6
  import recordStep from './record.js'
7
7
  import store from '../store.js'
8
+ import { mapTranspiledStackFrame } from '../utils/typescript.js'
8
9
 
9
10
  const STACK_LINE = 5
10
11
 
@@ -163,7 +164,13 @@ class Step {
163
164
  if (lines[STACK_LINE]) {
164
165
  let line = lines[STACK_LINE].trim()
165
166
 
166
- // Map .temp.mjs back to original .ts files using container's tsFileMapping
167
+ // Map .temp.mjs frames back to the original .ts source position using the
168
+ // inline source map emitted during transpilation (#5772)
169
+ if (line.includes('.temp.mjs')) {
170
+ line = mapTranspiledStackFrame(line) || line
171
+ }
172
+
173
+ // Fallback: map .temp.mjs back to original .ts files using container's tsFileMapping
167
174
  const fileMapping = store.tsFileMapping
168
175
  if (line.includes('.temp.mjs') && fileMapping) {
169
176
  for (const [tsFile, mjsFile] of fileMapping.entries()) {
package/lib/step/func.js CHANGED
@@ -21,7 +21,7 @@ class FuncStep extends BaseStep {
21
21
  // we wrap that function to track time and status
22
22
  // and disable it in dry run mode
23
23
  this.args = Array.prototype.slice.call(arguments)
24
- this.startTime = +Date.now()
24
+ if (!this.startTime) this.startTime = +Date.now()
25
25
 
26
26
  if (store.dryRun) {
27
27
  this.setStatus('success')
@@ -16,7 +16,7 @@ class HelperStep extends Step {
16
16
  */
17
17
  run() {
18
18
  this.args = Array.prototype.slice.call(arguments)
19
- this.startTime = +Date.now()
19
+ if (!this.startTime) this.startTime = +Date.now()
20
20
 
21
21
  if (store.dryRun) {
22
22
  this.setStatus('success')
@@ -4,28 +4,30 @@ import StepConfig from './config.js'
4
4
  import output from '../output.js'
5
5
  import store from '../store.js'
6
6
  import { TIMEOUT_ORDER } from '../timeout.js'
7
- import retryStep from './retry.js'
7
+ import retryStep, { releaseStepRetry } from './retry.js'
8
8
  import { fixErrorStack } from '../utils/typescript.js'
9
+
10
+ function applyStepConfig(step, stepConfig) {
11
+ const { opts, timeout, retry } = stepConfig.getConfig()
12
+
13
+ if (opts) {
14
+ output.debug(`Step ${step.title}: options applied ${JSON.stringify(opts)}`)
15
+ step.opts = { ...step.opts, ...opts }
16
+ store.stepOptions = step.opts
17
+ }
18
+ if (timeout) {
19
+ output.debug(`Step ${step.title} timeout ${timeout}s`)
20
+ step.setTimeout(timeout * 1000, TIMEOUT_ORDER.codeLimitTime)
21
+ }
22
+ if (retry) retryStep(step, retry)
23
+ }
24
+
9
25
  function recordStep(step, args) {
10
26
  step.status = 'queued'
11
27
 
12
28
  // apply step configuration
13
29
  const lastArg = args[args.length - 1]
14
- if (StepConfig.isStepConfig(lastArg)) {
15
- const stepConfig = args.pop()
16
- const { opts, timeout, retry } = stepConfig.getConfig()
17
-
18
- if (opts) {
19
- output.debug(`Step ${step.title}: options applied ${JSON.stringify(opts)}`)
20
- store.stepOptions = opts
21
- step.opts = opts
22
- }
23
- if (timeout) {
24
- output.debug(`Step ${step.title} timeout ${timeout}s`)
25
- step.setTimeout(timeout * 1000, TIMEOUT_ORDER.codeLimitTime)
26
- }
27
- if (retry) retryStep(retry)
28
- }
30
+ if (StepConfig.isStepConfig(lastArg)) applyStepConfig(step, args.pop())
29
31
 
30
32
  step.setArguments(args)
31
33
  // run async before step hooks
@@ -47,18 +49,20 @@ function recordStep(step, args) {
47
49
  },
48
50
  false,
49
51
  undefined,
50
- step.timeout,
52
+ () => step.timeout,
51
53
  )
52
54
 
53
55
  event.emit(event.step.after, step)
54
56
 
55
57
  recorder.add('step passed', () => {
58
+ releaseStepRetry(step)
56
59
  step.endTime = +Date.now()
57
60
  event.emit(event.step.passed, step, val)
58
61
  event.emit(event.step.finished, step)
59
62
  })
60
63
 
61
64
  recorder.catch(err => {
65
+ releaseStepRetry(step)
62
66
  step.status = 'failed'
63
67
  step.endTime = +Date.now()
64
68
 
@@ -79,4 +83,5 @@ function recordStep(step, args) {
79
83
  return recorder.promise()
80
84
  }
81
85
 
86
+ export { applyStepConfig }
82
87
  export default recordStep
package/lib/step/retry.js CHANGED
@@ -1,11 +1,18 @@
1
1
  import recorder from '../recorder.js'
2
- import event from '../event.js'
3
2
 
4
- function retryStep(opts) {
5
- if (opts === undefined) opts = 1
6
- recorder.retry(opts)
7
- // remove retry once the step passed
8
- recorder.add(() => event.dispatcher.once(event.step.finished, () => recorder.retries.pop()))
3
+ function retryStep(step, opts) {
4
+ releaseStepRetry(step)
5
+ let rule = opts
6
+ if (Number.isInteger(opts)) rule = { retries: opts }
7
+ recorder.retry(rule)
8
+ step.retryRule = rule
9
9
  }
10
10
 
11
+ function releaseStepRetry(step) {
12
+ if (!step.retryRule) return
13
+ recorder.retries = recorder.retries.filter(rule => rule !== step.retryRule)
14
+ step.retryRule = null
15
+ }
16
+
17
+ export { releaseStepRetry }
11
18
  export default retryStep
@@ -1,6 +1,7 @@
1
1
  import fs from 'fs'
2
2
  import path from 'path'
3
- import { pathToFileURL } from 'url'
3
+ import { pathToFileURL, fileURLToPath } from 'url'
4
+ import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'
4
5
 
5
6
  /**
6
7
  * Load tsconfig.json if it exists
@@ -65,8 +66,6 @@ function resolveTsPathAlias(importPath, tsConfig, configDir) {
65
66
  * @returns {Promise<{tempFile: string, allTempFiles: string[], fileMapping: any}>} - Main temp file and all temp files created
66
67
  */
67
68
  export async function transpileTypeScript(mainFilePath, typescript) {
68
- const { transpile } = typescript
69
-
70
69
  /**
71
70
  * Transpile a single TypeScript file to JavaScript
72
71
  * Injects CommonJS shims (require, module, exports, __dirname, __filename) as needed
@@ -74,17 +73,31 @@ export async function transpileTypeScript(mainFilePath, typescript) {
74
73
  const transpileTS = (filePath) => {
75
74
  const tsContent = fs.readFileSync(filePath, 'utf8')
76
75
 
77
- // Transpile TypeScript to JavaScript with ES module output
78
- let jsContent = transpile(tsContent, {
79
- module: 99, // ModuleKind.ESNext
80
- target: 99, // ScriptTarget.ESNext
81
- esModuleInterop: true,
82
- allowSyntheticDefaultImports: true,
83
- lib: ['lib.esnext.d.ts'], // Enable latest features including top-level await
84
- suppressOutputPathCheck: true,
85
- skipLibCheck: true,
76
+ // Transpile TypeScript to JavaScript with ES module output.
77
+ // transpileModule (unlike transpile) can emit a source map, which we inline
78
+ // so stack frames can later be mapped back to the original .ts positions.
79
+ const { outputText, sourceMapText } = typescript.transpileModule(tsContent, {
80
+ compilerOptions: {
81
+ module: 99, // ModuleKind.ESNext
82
+ target: 99, // ScriptTarget.ESNext
83
+ esModuleInterop: true,
84
+ allowSyntheticDefaultImports: true,
85
+ lib: ['lib.esnext.d.ts'], // Enable latest features including top-level await
86
+ suppressOutputPathCheck: true,
87
+ skipLibCheck: true,
88
+ sourceMap: true,
89
+ inlineSources: true,
90
+ },
91
+ fileName: path.resolve(filePath),
86
92
  })
87
93
 
94
+ // transpileModule appends an external sourceMappingURL comment; we inline the map instead
95
+ let jsContent = outputText.replace(/\/\/# sourceMappingURL=.*(\r?\n)?$/, '')
96
+ const sourceMap = JSON.parse(sourceMapText)
97
+ // transpileModule records only the base file name; store the absolute path
98
+ // so mapped stack frames can be resolved back to the source file
99
+ sourceMap.sources = [path.resolve(filePath)]
100
+
88
101
  // Check if the code uses CommonJS globals
89
102
  const usesCommonJSGlobals = /__dirname|__filename/.test(jsContent)
90
103
  const usesRequire = /\brequire\s*\(/.test(jsContent)
@@ -150,12 +163,22 @@ const __dirname = __dirname_fn(__filename);
150
163
 
151
164
  jsContent = esmGlobals + jsContent
152
165
 
166
+ // The injected shim shifts every generated line down; reflect that in the
167
+ // source map by prepending one empty mapping entry per shim line.
168
+ const shimLineCount = esmGlobals.split('\n').length - 1
169
+ sourceMap.mappings = `${';'.repeat(shimLineCount)}${sourceMap.mappings}`
170
+
153
171
  // If module.exports is used, we need to export it as default
154
172
  if (usesModuleExports) {
155
173
  jsContent += `\nexport default module.exports;\n`
156
174
  }
157
175
  }
158
176
 
177
+ // Append the source map inline so stack frames in the temp file can be
178
+ // mapped back to the original .ts positions (see mapTranspiledStackFrame)
179
+ const inlineMap = Buffer.from(JSON.stringify(sourceMap), 'utf8').toString('base64')
180
+ jsContent += `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${inlineMap}\n`
181
+
159
182
  return jsContent
160
183
  }
161
184
 
@@ -407,6 +430,57 @@ const __dirname = __dirname_fn(__filename);
407
430
  return { tempFile: tempFileUrl, allTempFiles, fileMapping: transpiledFiles }
408
431
  }
409
432
 
433
+ const sourceMapCache = new Map()
434
+
435
+ function getInlineSourceMap(tempFilePath) {
436
+ if (sourceMapCache.has(tempFilePath)) return sourceMapCache.get(tempFilePath)
437
+
438
+ let traceMap = null
439
+ try {
440
+ const content = fs.readFileSync(tempFilePath, 'utf8')
441
+ const match = /\/\/# sourceMappingURL=data:application\/json;charset=utf-8;base64,([A-Za-z0-9+/=]+)\s*$/.exec(content)
442
+ if (match) {
443
+ traceMap = new TraceMap(JSON.parse(Buffer.from(match[1], 'base64').toString('utf8')))
444
+ }
445
+ } catch {
446
+ // No usable inline source map; callers fall back to path-only mapping
447
+ }
448
+
449
+ sourceMapCache.set(tempFilePath, traceMap)
450
+ return traceMap
451
+ }
452
+
453
+ /**
454
+ * Map a stack frame pointing into a transpiled `.temp.mjs` file back to the
455
+ * original TypeScript source position, using the inline source map emitted
456
+ * during transpilation.
457
+ *
458
+ * @param {string} frame - Single stack frame line, e.g. `at Object.open (file:///path/foo.123.temp.mjs:4:11)`
459
+ * @returns {string|null} - Rewritten frame with the original source position, or null when mapping is not possible
460
+ */
461
+ export function mapTranspiledStackFrame(frame) {
462
+ const match = /\((file:\/\/)?([^()]*?\.temp\.mjs):(\d+):(\d+)\)/.exec(frame)
463
+ if (!match) return null
464
+
465
+ const [, isFileUrl, fileRef, genLine, genColumn] = match
466
+ let tempFilePath = fileRef
467
+ if (isFileUrl) {
468
+ try {
469
+ tempFilePath = fileURLToPath(`${isFileUrl}${fileRef}`)
470
+ } catch {
471
+ return null
472
+ }
473
+ }
474
+ const traceMap = getInlineSourceMap(tempFilePath)
475
+ if (!traceMap) return null
476
+
477
+ // V8 reports 1-based columns, trace-mapping expects 0-based
478
+ const pos = originalPositionFor(traceMap, { line: Number(genLine), column: Number(genColumn) - 1 })
479
+ if (!pos || pos.line == null || !pos.source) return null
480
+
481
+ return frame.replace(match[0], `(${pos.source}:${pos.line}:${pos.column + 1})`)
482
+ }
483
+
410
484
  /**
411
485
  * Map error stack traces from temp .mjs files back to original .ts files
412
486
  * @param {Error} error - The error object to fix