msw 2.0.13 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/cli/index.js +11 -3
  2. package/cli/init.js +126 -73
  3. package/config/scripts/postinstall.js +8 -20
  4. package/lib/browser/index.js +111 -176
  5. package/lib/browser/index.js.map +1 -1
  6. package/lib/browser/index.mjs +111 -179
  7. package/lib/browser/index.mjs.map +1 -1
  8. package/lib/core/{GraphQLHandler-SHlRCcy4.d.ts → GraphQLHandler-LZ8jH42-.d.ts} +4 -2
  9. package/lib/core/{GraphQLHandler-zlmUDnN6.d.mts → GraphQLHandler-c0pfLv8e.d.mts} +4 -2
  10. package/lib/core/HttpResponse.d.mts +1 -1
  11. package/lib/core/HttpResponse.d.ts +1 -1
  12. package/lib/core/{RequestHandler-rBDJQrEf.d.ts → RequestHandler-SdFwV297.d.ts} +11 -4
  13. package/lib/core/{RequestHandler-vxZdj6Tw.d.mts → RequestHandler-hEwneHZE.d.mts} +11 -4
  14. package/lib/core/SetupApi.d.mts +1 -1
  15. package/lib/core/SetupApi.d.ts +1 -1
  16. package/lib/core/SetupApi.js +5 -0
  17. package/lib/core/SetupApi.js.map +1 -1
  18. package/lib/core/SetupApi.mjs +5 -0
  19. package/lib/core/SetupApi.mjs.map +1 -1
  20. package/lib/core/delay.js +24 -46
  21. package/lib/core/delay.js.map +1 -1
  22. package/lib/core/delay.mjs +24 -46
  23. package/lib/core/delay.mjs.map +1 -1
  24. package/lib/core/graphql.d.mts +11 -9
  25. package/lib/core/graphql.d.ts +11 -9
  26. package/lib/core/graphql.js +3 -19
  27. package/lib/core/graphql.js.map +1 -1
  28. package/lib/core/graphql.mjs +3 -21
  29. package/lib/core/graphql.mjs.map +1 -1
  30. package/lib/core/handlers/GraphQLHandler.d.mts +2 -2
  31. package/lib/core/handlers/GraphQLHandler.d.ts +2 -2
  32. package/lib/core/handlers/GraphQLHandler.js +52 -77
  33. package/lib/core/handlers/GraphQLHandler.js.map +1 -1
  34. package/lib/core/handlers/GraphQLHandler.mjs +52 -77
  35. package/lib/core/handlers/GraphQLHandler.mjs.map +1 -1
  36. package/lib/core/handlers/HttpHandler.d.mts +1 -1
  37. package/lib/core/handlers/HttpHandler.d.ts +1 -1
  38. package/lib/core/handlers/HttpHandler.js +29 -55
  39. package/lib/core/handlers/HttpHandler.js.map +1 -1
  40. package/lib/core/handlers/HttpHandler.mjs +29 -55
  41. package/lib/core/handlers/HttpHandler.mjs.map +1 -1
  42. package/lib/core/handlers/RequestHandler.d.mts +1 -1
  43. package/lib/core/handlers/RequestHandler.d.ts +1 -1
  44. package/lib/core/handlers/RequestHandler.js +79 -103
  45. package/lib/core/handlers/RequestHandler.js.map +1 -1
  46. package/lib/core/handlers/RequestHandler.mjs +79 -105
  47. package/lib/core/handlers/RequestHandler.mjs.map +1 -1
  48. package/lib/core/http.d.mts +13 -11
  49. package/lib/core/http.d.ts +13 -11
  50. package/lib/core/http.js.map +1 -1
  51. package/lib/core/http.mjs.map +1 -1
  52. package/lib/core/index.d.mts +4 -4
  53. package/lib/core/index.d.ts +4 -4
  54. package/lib/core/index.js.map +1 -1
  55. package/lib/core/index.mjs.map +1 -1
  56. package/lib/core/sharedOptions.d.mts +1 -1
  57. package/lib/core/sharedOptions.d.ts +1 -1
  58. package/lib/core/utils/HttpResponse/decorators.d.mts +1 -1
  59. package/lib/core/utils/HttpResponse/decorators.d.ts +1 -1
  60. package/lib/core/utils/HttpResponse/decorators.js +7 -24
  61. package/lib/core/utils/HttpResponse/decorators.js.map +1 -1
  62. package/lib/core/utils/HttpResponse/decorators.mjs +7 -26
  63. package/lib/core/utils/HttpResponse/decorators.mjs.map +1 -1
  64. package/lib/core/utils/getResponse.d.mts +1 -1
  65. package/lib/core/utils/getResponse.d.ts +1 -1
  66. package/lib/core/utils/getResponse.js +11 -26
  67. package/lib/core/utils/getResponse.js.map +1 -1
  68. package/lib/core/utils/getResponse.mjs +11 -26
  69. package/lib/core/utils/getResponse.mjs.map +1 -1
  70. package/lib/core/utils/handleRequest.d.mts +1 -1
  71. package/lib/core/utils/handleRequest.d.ts +1 -1
  72. package/lib/core/utils/handleRequest.js +49 -72
  73. package/lib/core/utils/handleRequest.js.map +1 -1
  74. package/lib/core/utils/handleRequest.mjs +49 -72
  75. package/lib/core/utils/handleRequest.mjs.map +1 -1
  76. package/lib/core/utils/internal/Disposable.js +3 -27
  77. package/lib/core/utils/internal/Disposable.js.map +1 -1
  78. package/lib/core/utils/internal/Disposable.mjs +3 -27
  79. package/lib/core/utils/internal/Disposable.mjs.map +1 -1
  80. package/lib/core/utils/internal/parseGraphQLRequest.d.mts +2 -2
  81. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +2 -2
  82. package/lib/core/utils/internal/parseGraphQLRequest.js +72 -112
  83. package/lib/core/utils/internal/parseGraphQLRequest.js.map +1 -1
  84. package/lib/core/utils/internal/parseGraphQLRequest.mjs +72 -113
  85. package/lib/core/utils/internal/parseGraphQLRequest.mjs.map +1 -1
  86. package/lib/core/utils/internal/parseMultipartData.d.mts +1 -1
  87. package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
  88. package/lib/core/utils/internal/parseMultipartData.js +3 -4
  89. package/lib/core/utils/internal/parseMultipartData.js.map +1 -1
  90. package/lib/core/utils/internal/parseMultipartData.mjs +3 -4
  91. package/lib/core/utils/internal/parseMultipartData.mjs.map +1 -1
  92. package/lib/core/utils/internal/requestHandlerUtils.d.mts +1 -1
  93. package/lib/core/utils/internal/requestHandlerUtils.d.ts +1 -1
  94. package/lib/core/utils/internal/tryCatch.js +1 -1
  95. package/lib/core/utils/internal/tryCatch.js.map +1 -1
  96. package/lib/core/utils/internal/tryCatch.mjs +1 -1
  97. package/lib/core/utils/internal/tryCatch.mjs.map +1 -1
  98. package/lib/core/utils/logging/serializeRequest.js +9 -31
  99. package/lib/core/utils/logging/serializeRequest.js.map +1 -1
  100. package/lib/core/utils/logging/serializeRequest.mjs +9 -31
  101. package/lib/core/utils/logging/serializeRequest.mjs.map +1 -1
  102. package/lib/core/utils/logging/serializeResponse.js +11 -33
  103. package/lib/core/utils/logging/serializeResponse.js.map +1 -1
  104. package/lib/core/utils/logging/serializeResponse.mjs +11 -33
  105. package/lib/core/utils/logging/serializeResponse.mjs.map +1 -1
  106. package/lib/core/utils/request/getRequestCookies.js +9 -18
  107. package/lib/core/utils/request/getRequestCookies.js.map +1 -1
  108. package/lib/core/utils/request/getRequestCookies.mjs +9 -20
  109. package/lib/core/utils/request/getRequestCookies.mjs.map +1 -1
  110. package/lib/core/utils/request/onUnhandledRequest.d.mts +1 -1
  111. package/lib/core/utils/request/onUnhandledRequest.d.ts +1 -1
  112. package/lib/core/utils/request/onUnhandledRequest.js +62 -84
  113. package/lib/core/utils/request/onUnhandledRequest.js.map +1 -1
  114. package/lib/core/utils/request/onUnhandledRequest.mjs +62 -84
  115. package/lib/core/utils/request/onUnhandledRequest.mjs.map +1 -1
  116. package/lib/core/utils/request/readResponseCookies.js +1 -18
  117. package/lib/core/utils/request/readResponseCookies.js.map +1 -1
  118. package/lib/core/utils/request/readResponseCookies.mjs +1 -20
  119. package/lib/core/utils/request/readResponseCookies.mjs.map +1 -1
  120. package/lib/iife/index.js +679 -958
  121. package/lib/iife/index.js.map +1 -1
  122. package/lib/mockServiceWorker.js +2 -2
  123. package/lib/native/index.js +5 -23
  124. package/lib/native/index.js.map +1 -1
  125. package/lib/native/index.mjs +5 -24
  126. package/lib/native/index.mjs.map +1 -1
  127. package/lib/node/index.js +5 -23
  128. package/lib/node/index.js.map +1 -1
  129. package/lib/node/index.mjs +5 -24
  130. package/lib/node/index.mjs.map +1 -1
  131. package/package.json +32 -37
  132. package/src/browser/setupWorker/setupWorker.ts +6 -0
  133. package/src/browser/setupWorker/start/createStartHandler.ts +0 -8
  134. package/src/core/graphql.ts +24 -16
  135. package/src/core/handlers/GraphQLHandler.test.ts +15 -0
  136. package/src/core/handlers/GraphQLHandler.ts +8 -5
  137. package/src/core/handlers/RequestHandler.ts +37 -13
  138. package/src/core/http.ts +27 -14
  139. package/src/core/index.ts +3 -0
  140. package/src/core/utils/getResponse.ts +12 -6
  141. package/src/core/utils/handleRequest.test.ts +20 -0
  142. package/src/core/utils/handleRequest.ts +4 -3
package/cli/index.js CHANGED
@@ -4,21 +4,29 @@ const yargs = require('yargs')
4
4
  yargs
5
5
  .usage('$0 <cmd> [args]')
6
6
  .command(
7
- 'init <publicDir>',
7
+ 'init',
8
8
  'Initializes Mock Service Worker at the specified directory',
9
9
  (yargs) => {
10
10
  yargs
11
+
11
12
  .positional('publicDir', {
12
13
  type: 'string',
13
14
  description: 'Relative path to the public directory',
14
- required: true,
15
+ demandOption: false,
15
16
  normalize: true,
16
17
  })
17
- .example('init', 'msw init public')
18
18
  .option('save', {
19
19
  type: 'boolean',
20
20
  description: 'Save the worker directory in your package.json',
21
21
  })
22
+ .option('cwd', {
23
+ type: 'string',
24
+ description: 'Custom current worker directory',
25
+ normalize: true,
26
+ })
27
+ .example('msw init')
28
+ .example('msw init ./public')
29
+ .example('msw init ./static --save')
22
30
  },
23
31
  require('./init'),
24
32
  )
package/cli/init.js CHANGED
@@ -6,116 +6,169 @@ const inquirer = require('inquirer')
6
6
  const invariant = require('./invariant')
7
7
  const { SERVICE_WORKER_BUILD_PATH } = require('../config/constants')
8
8
 
9
- const CWD = process.cwd()
10
-
11
9
  module.exports = async function init(args) {
12
- const { publicDir, save } = args
10
+ const [, publicDir] = args._
11
+ const CWD = args.cwd || process.cwd()
12
+
13
+ const packageJsonPath = path.resolve(CWD, 'package.json')
14
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
15
+ const savedWorkerDirectories = Array.prototype.concat(
16
+ (packageJson.msw && packageJson.msw.workerDirectory) || [],
17
+ )
18
+
19
+ if (publicDir) {
20
+ // If the public directory was provided, copy the worker script
21
+ // to that directory only. Even if there are paths stored in "msw.workerDirectory",
22
+ // those will not be touched.
23
+ await copyWorkerScript(publicDir, CWD)
24
+ const relativePublicDir = toRelative(publicDir, CWD)
25
+ printSuccessMessage([publicDir])
26
+
27
+ if (args.save) {
28
+ // Only save the public path if it's not already saved in "package.json".
29
+ if (!savedWorkerDirectories.includes(relativePublicDir)) {
30
+ saveWorkerDirectory(packageJsonPath, relativePublicDir)
31
+ }
32
+ }
33
+ // Explicitly check if "save" was not provided (was null).
34
+ // You can also provide the "--no-save" option, and then "args.save"
35
+ // will equal to false.
36
+ else if (args.save == null) {
37
+ console.log(`\
38
+ ${chalk.cyan(
39
+ 'INFO',
40
+ )} In order to ease the future updates to the worker script,
41
+ we recommend saving the path to the worker directory in your package.json.`)
42
+
43
+ // If the "--save" flag was not provided, prompt to save
44
+ // the public path.
45
+ promptWorkerDirectoryUpdate(
46
+ `Do you wish to save "${relativePublicDir}" as the worker directory?`,
47
+ packageJsonPath,
48
+ relativePublicDir,
49
+ )
50
+ }
51
+
52
+ return
53
+ }
54
+
55
+ // Calling "init" without a public directory but with the "--save" flag
56
+ // is no-op.
57
+ invariant(
58
+ args.save == null,
59
+ 'Failed to copy the worker script: cannot call the "init" command without a public directory but with the "--save" flag. Either drop the "--save" flag to copy the worker script to all paths listed in "msw.workerDirectory", or add an explicit public directory to the command, like "npx msw init ./public".',
60
+ )
13
61
 
62
+ // If the public directory was not provided, check any existing
63
+ // paths in "msw.workerDirectory". When called without the public
64
+ // directory, the "init" command must copy the worker script
65
+ // to all the paths stored in "msw.workerDirectory".
66
+ if (savedWorkerDirectories.length > 0) {
67
+ const copyResults = await Promise.allSettled(
68
+ savedWorkerDirectories.map((destination) => {
69
+ return copyWorkerScript(destination, CWD).catch((error) => {
70
+ // Inject the absolute destination path onto the copy function rejections
71
+ // so it's available in the failed paths array below.
72
+ throw [toAbsolute(destination, CWD), error]
73
+ })
74
+ }),
75
+ )
76
+ const successfulPaths = copyResults
77
+ .filter((result) => result.status === 'fulfilled')
78
+ .map((result) => result.value)
79
+ const failedPathsWithErrors = copyResults
80
+ .filter((result) => result.status === 'rejected')
81
+ .map((result) => result.reason)
82
+
83
+ // Notify about failed copies, if any.
84
+ if (failedPathsWithErrors.length > 0) {
85
+ printFailureMessage(failedPathsWithErrors)
86
+ }
87
+
88
+ // Notify about successful copies, if any.
89
+ if (successfulPaths.length > 0) {
90
+ printSuccessMessage(successfulPaths)
91
+ }
92
+ }
93
+ }
94
+
95
+ function toRelative(absolutePath, cwd) {
96
+ return path.relative(cwd, absolutePath)
97
+ }
98
+
99
+ function toAbsolute(maybeAbsolutePath, cwd) {
100
+ return path.isAbsolute(maybeAbsolutePath)
101
+ ? maybeAbsolutePath
102
+ : path.resolve(cwd, maybeAbsolutePath)
103
+ }
104
+
105
+ async function copyWorkerScript(destination, cwd) {
14
106
  // When running as a part of "postinstall" script, "cwd" equals the library's directory.
15
107
  // The "postinstall" script resolves the right absolute public directory path.
16
- const absolutePublicDir = path.isAbsolute(publicDir)
17
- ? publicDir
18
- : path.resolve(CWD, publicDir)
19
- const relativePublicDir = path.relative(CWD, absolutePublicDir)
20
- const dirExists = fs.existsSync(absolutePublicDir)
108
+ const absolutePublicDir = toAbsolute(destination, cwd)
21
109
 
22
- if (!dirExists) {
110
+ if (!fs.existsSync(absolutePublicDir)) {
23
111
  // Try to create the directory if it doesn't exist
24
112
  const createDirectoryResult = await until(() =>
25
113
  fs.promises.mkdir(absolutePublicDir, { recursive: true }),
26
114
  )
115
+
27
116
  invariant(
28
117
  createDirectoryResult.error == null,
29
- 'Failed to create a Service Worker at "%s": directory does not exist and could not be created.\nMake sure to include a relative path to the root directory of your server.\n\nSee the original error below:\n%s',
118
+ 'Failed to copy the worker script at "%s": directory does not exist and could not be created.\nMake sure to include a relative path to the public directory of your application.\n\nSee the original error below:\n%s',
30
119
  absolutePublicDir,
31
120
  createDirectoryResult.error,
32
121
  )
33
122
  }
34
123
 
35
- console.log(
36
- 'Initializing the Mock Service Worker at "%s"...',
37
- absolutePublicDir,
38
- )
124
+ console.log('Copying the worker script at "%s"...', absolutePublicDir)
39
125
 
40
126
  const serviceWorkerFilename = path.basename(SERVICE_WORKER_BUILD_PATH)
41
127
  const swDestFilepath = path.resolve(absolutePublicDir, serviceWorkerFilename)
42
128
 
43
129
  fs.copyFileSync(SERVICE_WORKER_BUILD_PATH, swDestFilepath)
44
130
 
45
- console.log(`
46
- ${chalk.green('Service Worker successfully created!')}
47
- ${chalk.gray(swDestFilepath)}
131
+ return swDestFilepath
132
+ }
48
133
 
49
- Continue by creating a mocking definition module in your application:
134
+ function printSuccessMessage(paths) {
135
+ console.log(`
136
+ ${chalk.green('Worker script successfully copied!')}
137
+ ${paths.map((path) => chalk.gray(` - ${path}\n`))}
138
+ Continue by describing the network in your application:
139
+
50
140
 
51
- ${chalk.cyan.bold('https://mswjs.io/docs/getting-started/mocks')}
141
+ ${chalk.cyan.bold('https://mswjs.io/docs/getting-started')}
52
142
  `)
143
+ }
53
144
 
54
- const packageJsonPath = path.resolve(CWD, 'package.json')
55
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
56
- const { msw: mswConfig } = packageJson
57
-
58
- if (mswConfig && mswConfig.workerDirectory === relativePublicDir) {
59
- return
60
- }
61
-
62
- // When called `msw init --no-save` do not show the save suggestions.
63
- if (save === false) {
64
- return
65
- }
66
-
67
- if (!mswConfig) {
68
- console.log(`\
69
- ${chalk.cyan('INFO')} In order to ease the future updates to the worker script,
70
- we recommend saving the path to the worker directory in your package.json.
71
- `)
72
-
73
- if (save) {
74
- return saveWorkerDirectory(packageJsonPath, relativePublicDir)
75
- }
76
-
77
- return promptWorkerDirectoryUpdate(
78
- `Do you wish to save "${relativePublicDir}" as the worker directory?`,
79
- packageJsonPath,
80
- relativePublicDir,
81
- )
82
- }
83
-
84
- if (mswConfig.workerDirectory !== relativePublicDir) {
85
- console.log(
86
- `\
87
- ${chalk.yellowBright(
88
- 'WARN',
89
- )} The "msw.workerDirectory" in your package.json ("%s")
90
- is different from the worker directory used right now ("%s").
91
- `,
92
- mswConfig.workerDirectory,
93
- relativePublicDir,
94
- )
95
-
96
- if (save) {
97
- return saveWorkerDirectory(packageJsonPath, relativePublicDir)
98
- }
99
-
100
- return promptWorkerDirectoryUpdate(
101
- `Do you wish to use "${relativePublicDir}" instead of "${mswConfig.workerDirectory}" as the worker directory?`,
102
- packageJsonPath,
103
- relativePublicDir,
104
- )
105
- }
145
+ function printFailureMessage(pathsWithErrors) {
146
+ console.error(`\
147
+ ${chalk.red('Copying the worker script failed at following paths:')}
148
+ ${pathsWithErrors
149
+ .map(([path, error]) => chalk.gray(` - ${path}`) + '\n' + ` ${error}`)
150
+ .join('\n\n')}
151
+ `)
106
152
  }
107
153
 
108
154
  function saveWorkerDirectory(packageJsonPath, publicDir) {
109
155
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
110
156
 
111
157
  console.log(
112
- chalk.gray('Writing "msw.workerDirectory" to "%s"...'),
158
+ chalk.gray('Updating "msw.workerDirectory" at "%s"...'),
113
159
  packageJsonPath,
114
160
  )
115
161
 
162
+ const prevWorkerDirectory = Array.prototype.concat(
163
+ (packageJson.msw && packageJson.msw.workerDirectory) || [],
164
+ )
165
+ const nextWorkerDirectory = Array.from(
166
+ new Set(prevWorkerDirectory).add(publicDir),
167
+ )
168
+
116
169
  const nextPackageJson = Object.assign({}, packageJson, {
117
170
  msw: {
118
- workerDirectory: publicDir,
171
+ workerDirectory: nextWorkerDirectory,
119
172
  },
120
173
  })
121
174
 
@@ -7,8 +7,7 @@ const { execSync } = require('child_process')
7
7
  // NPM stores the parent project directory in the "INIT_CWD" env variable.
8
8
  const parentPackageCwd = process.env.INIT_CWD
9
9
 
10
- function postinstall() {
11
- // 1. Check if "package.json" has "msw.workerDirectory" property set.
10
+ function postInstall() {
12
11
  const packageJson = JSON.parse(
13
12
  fs.readFileSync(path.resolve(parentPackageCwd, 'package.json'), 'utf8'),
14
13
  )
@@ -17,32 +16,21 @@ function postinstall() {
17
16
  return
18
17
  }
19
18
 
20
- // 2. Check if the worker directory is an existing path.
21
- const { workerDirectory } = packageJson.msw
22
- const absoluteWorkerDirectory = path.resolve(
23
- parentPackageCwd,
24
- workerDirectory,
25
- )
26
-
27
- if (!fs.existsSync(absoluteWorkerDirectory)) {
28
- return console.error(
29
- `[MSW] Failed to automatically update the worker script at "%s": given path does not exist.`,
30
- workerDirectory,
31
- )
32
- }
33
-
34
- // 3. Update the worker script.
35
19
  const cliExecutable = path.resolve(process.cwd(), 'cli/index.js')
36
20
 
37
21
  try {
38
- execSync(`node ${cliExecutable} init ${absoluteWorkerDirectory}`, {
22
+ /**
23
+ * @note Call the "init" command directly. It will now copy the worker script
24
+ * to all saved paths in "msw.workerDirectory"
25
+ */
26
+ execSync(`node ${cliExecutable} init`, {
39
27
  cwd: parentPackageCwd,
40
28
  })
41
29
  } catch (error) {
42
30
  console.error(
43
- `[MSW] Failed to automatically update the worker script:\n${error}`,
31
+ `[MSW] Failed to automatically update the worker script.\n\n${error}`,
44
32
  )
45
33
  }
46
34
  }
47
35
 
48
- postinstall()
36
+ postInstall()