@strapi/core 0.0.0-experimental.aa8f064c5e2c0138b780746dc4455c060da87829 → 0.0.0-experimental.ab7bb8f8d3c8871e51e0720c5d36d826309f80b5

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.

Potentially problematic release.


This version of @strapi/core might be problematic. Click here for more details.

Files changed (281) hide show
  1. package/dist/Strapi.d.ts +1 -0
  2. package/dist/Strapi.d.ts.map +1 -1
  3. package/dist/Strapi.js +22 -5
  4. package/dist/Strapi.js.map +1 -1
  5. package/dist/Strapi.mjs +22 -5
  6. package/dist/Strapi.mjs.map +1 -1
  7. package/dist/configuration/config-loader.js.map +1 -1
  8. package/dist/configuration/config-loader.mjs.map +1 -1
  9. package/dist/configuration/urls.js.map +1 -1
  10. package/dist/configuration/urls.mjs.map +1 -1
  11. package/dist/constants.d.ts +3 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +6 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/constants.mjs +4 -0
  16. package/dist/constants.mjs.map +1 -0
  17. package/dist/container.js.map +1 -1
  18. package/dist/container.mjs.map +1 -1
  19. package/dist/core-api/controller/index.d.ts.map +1 -1
  20. package/dist/core-api/controller/index.js +2 -1
  21. package/dist/core-api/controller/index.js.map +1 -1
  22. package/dist/core-api/controller/index.mjs +2 -1
  23. package/dist/core-api/controller/index.mjs.map +1 -1
  24. package/dist/core-api/controller/transform.d.ts +3 -2
  25. package/dist/core-api/controller/transform.d.ts.map +1 -1
  26. package/dist/core-api/controller/transform.js +13 -3
  27. package/dist/core-api/controller/transform.js.map +1 -1
  28. package/dist/core-api/controller/transform.mjs +13 -3
  29. package/dist/core-api/controller/transform.mjs.map +1 -1
  30. package/dist/core-api/routes/index.d.ts +4 -22
  31. package/dist/core-api/routes/index.d.ts.map +1 -1
  32. package/dist/core-api/routes/index.js +150 -8
  33. package/dist/core-api/routes/index.js.map +1 -1
  34. package/dist/core-api/routes/index.mjs +131 -8
  35. package/dist/core-api/routes/index.mjs.map +1 -1
  36. package/dist/core-api/routes/validation/attributes.d.ts +244 -0
  37. package/dist/core-api/routes/validation/attributes.d.ts.map +1 -0
  38. package/dist/core-api/routes/validation/attributes.js +560 -0
  39. package/dist/core-api/routes/validation/attributes.js.map +1 -0
  40. package/dist/core-api/routes/validation/attributes.mjs +521 -0
  41. package/dist/core-api/routes/validation/attributes.mjs.map +1 -0
  42. package/dist/core-api/routes/validation/common.d.ts +105 -0
  43. package/dist/core-api/routes/validation/common.d.ts.map +1 -0
  44. package/dist/core-api/routes/validation/common.js +116 -0
  45. package/dist/core-api/routes/validation/common.js.map +1 -0
  46. package/dist/core-api/routes/validation/common.mjs +95 -0
  47. package/dist/core-api/routes/validation/common.mjs.map +1 -0
  48. package/dist/core-api/routes/validation/component.d.ts +34 -0
  49. package/dist/core-api/routes/validation/component.d.ts.map +1 -0
  50. package/dist/core-api/routes/validation/component.js +45 -0
  51. package/dist/core-api/routes/validation/component.js.map +1 -0
  52. package/dist/core-api/routes/validation/component.mjs +43 -0
  53. package/dist/core-api/routes/validation/component.mjs.map +1 -0
  54. package/dist/core-api/routes/validation/constants.d.ts +8 -0
  55. package/dist/core-api/routes/validation/constants.d.ts.map +1 -0
  56. package/dist/core-api/routes/validation/constants.js +18 -0
  57. package/dist/core-api/routes/validation/constants.js.map +1 -0
  58. package/dist/core-api/routes/validation/constants.mjs +16 -0
  59. package/dist/core-api/routes/validation/constants.mjs.map +1 -0
  60. package/dist/core-api/routes/validation/content-type.d.ts +128 -0
  61. package/dist/core-api/routes/validation/content-type.d.ts.map +1 -0
  62. package/dist/core-api/routes/validation/content-type.js +201 -0
  63. package/dist/core-api/routes/validation/content-type.js.map +1 -0
  64. package/dist/core-api/routes/validation/content-type.mjs +180 -0
  65. package/dist/core-api/routes/validation/content-type.mjs.map +1 -0
  66. package/dist/core-api/routes/validation/index.d.ts +5 -0
  67. package/dist/core-api/routes/validation/index.d.ts.map +1 -0
  68. package/dist/core-api/routes/validation/mappers.d.ts +105 -0
  69. package/dist/core-api/routes/validation/mappers.d.ts.map +1 -0
  70. package/dist/core-api/routes/validation/mappers.js +273 -0
  71. package/dist/core-api/routes/validation/mappers.js.map +1 -0
  72. package/dist/core-api/routes/validation/mappers.mjs +249 -0
  73. package/dist/core-api/routes/validation/mappers.mjs.map +1 -0
  74. package/dist/core-api/routes/validation/utils.d.ts +47 -0
  75. package/dist/core-api/routes/validation/utils.d.ts.map +1 -0
  76. package/dist/core-api/routes/validation/utils.js +128 -0
  77. package/dist/core-api/routes/validation/utils.js.map +1 -0
  78. package/dist/core-api/routes/validation/utils.mjs +106 -0
  79. package/dist/core-api/routes/validation/utils.mjs.map +1 -0
  80. package/dist/core-api/service/collection-type.js.map +1 -1
  81. package/dist/core-api/service/collection-type.mjs.map +1 -1
  82. package/dist/core-api/service/single-type.js.map +1 -1
  83. package/dist/core-api/service/single-type.mjs.map +1 -1
  84. package/dist/domain/content-type/index.d.ts.map +1 -1
  85. package/dist/domain/content-type/index.js +17 -1
  86. package/dist/domain/content-type/index.js.map +1 -1
  87. package/dist/domain/content-type/index.mjs +17 -1
  88. package/dist/domain/content-type/index.mjs.map +1 -1
  89. package/dist/domain/module/index.d.ts.map +1 -1
  90. package/dist/domain/module/index.js +3 -0
  91. package/dist/domain/module/index.js.map +1 -1
  92. package/dist/domain/module/index.mjs +3 -0
  93. package/dist/domain/module/index.mjs.map +1 -1
  94. package/dist/ee/index.js.map +1 -1
  95. package/dist/ee/index.mjs.map +1 -1
  96. package/dist/ee/license.js +1 -2
  97. package/dist/ee/license.js.map +1 -1
  98. package/dist/ee/license.mjs +1 -2
  99. package/dist/ee/license.mjs.map +1 -1
  100. package/dist/factories.d.ts +3 -1
  101. package/dist/factories.d.ts.map +1 -1
  102. package/dist/factories.js +10 -2
  103. package/dist/factories.js.map +1 -1
  104. package/dist/factories.mjs +10 -3
  105. package/dist/factories.mjs.map +1 -1
  106. package/dist/loaders/apis.js.map +1 -1
  107. package/dist/loaders/apis.mjs.map +1 -1
  108. package/dist/loaders/components.js.map +1 -1
  109. package/dist/loaders/components.mjs.map +1 -1
  110. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  111. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  112. package/dist/loaders/plugins/index.js +1 -1
  113. package/dist/loaders/plugins/index.js.map +1 -1
  114. package/dist/loaders/plugins/index.mjs +1 -1
  115. package/dist/loaders/plugins/index.mjs.map +1 -1
  116. package/dist/loaders/src-index.js.map +1 -1
  117. package/dist/loaders/src-index.mjs.map +1 -1
  118. package/dist/middlewares/cors.d.ts +9 -1
  119. package/dist/middlewares/cors.d.ts.map +1 -1
  120. package/dist/middlewares/cors.js +39 -17
  121. package/dist/middlewares/cors.js.map +1 -1
  122. package/dist/middlewares/cors.mjs +39 -18
  123. package/dist/middlewares/cors.mjs.map +1 -1
  124. package/dist/middlewares/logger.js.map +1 -1
  125. package/dist/middlewares/logger.mjs.map +1 -1
  126. package/dist/middlewares/response-time.js.map +1 -1
  127. package/dist/middlewares/response-time.mjs.map +1 -1
  128. package/dist/middlewares/security.d.ts.map +1 -1
  129. package/dist/middlewares/security.js +2 -15
  130. package/dist/middlewares/security.js.map +1 -1
  131. package/dist/middlewares/security.mjs +2 -15
  132. package/dist/middlewares/security.mjs.map +1 -1
  133. package/dist/migrations/database/5.0.0-discard-drafts.js +1 -1
  134. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  135. package/dist/migrations/database/5.0.0-discard-drafts.mjs +1 -1
  136. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  137. package/dist/migrations/first-published-at.d.ts +4 -0
  138. package/dist/migrations/first-published-at.d.ts.map +1 -0
  139. package/dist/migrations/first-published-at.js +51 -0
  140. package/dist/migrations/first-published-at.js.map +1 -0
  141. package/dist/migrations/first-published-at.mjs +49 -0
  142. package/dist/migrations/first-published-at.mjs.map +1 -0
  143. package/dist/migrations/index.d.ts.map +1 -1
  144. package/dist/migrations/index.js +5 -0
  145. package/dist/migrations/index.js.map +1 -1
  146. package/dist/migrations/index.mjs +5 -0
  147. package/dist/migrations/index.mjs.map +1 -1
  148. package/dist/package.json.js +19 -16
  149. package/dist/package.json.js.map +1 -1
  150. package/dist/package.json.mjs +19 -16
  151. package/dist/package.json.mjs.map +1 -1
  152. package/dist/providers/index.d.ts.map +1 -1
  153. package/dist/providers/index.js +2 -0
  154. package/dist/providers/index.js.map +1 -1
  155. package/dist/providers/index.mjs +2 -0
  156. package/dist/providers/index.mjs.map +1 -1
  157. package/dist/providers/session-manager.d.ts +3 -0
  158. package/dist/providers/session-manager.d.ts.map +1 -0
  159. package/dist/providers/session-manager.js +23 -0
  160. package/dist/providers/session-manager.js.map +1 -0
  161. package/dist/providers/session-manager.mjs +21 -0
  162. package/dist/providers/session-manager.mjs.map +1 -0
  163. package/dist/registries/apis.js.map +1 -1
  164. package/dist/registries/apis.mjs.map +1 -1
  165. package/dist/registries/custom-fields.js.map +1 -1
  166. package/dist/registries/custom-fields.mjs.map +1 -1
  167. package/dist/registries/namespace.js.map +1 -1
  168. package/dist/registries/namespace.mjs.map +1 -1
  169. package/dist/registries/plugins.js.map +1 -1
  170. package/dist/registries/plugins.mjs.map +1 -1
  171. package/dist/registries/policies.js.map +1 -1
  172. package/dist/registries/policies.mjs.map +1 -1
  173. package/dist/services/config.js.map +1 -1
  174. package/dist/services/config.mjs.map +1 -1
  175. package/dist/services/content-api/index.d.ts +1 -1
  176. package/dist/services/content-api/index.d.ts.map +1 -1
  177. package/dist/services/content-api/index.js +1 -1
  178. package/dist/services/content-api/index.js.map +1 -1
  179. package/dist/services/content-api/index.mjs +2 -2
  180. package/dist/services/content-api/index.mjs.map +1 -1
  181. package/dist/services/content-api/permissions/index.js.map +1 -1
  182. package/dist/services/content-api/permissions/index.mjs.map +1 -1
  183. package/dist/services/content-source-maps.d.ts +13 -0
  184. package/dist/services/content-source-maps.d.ts.map +1 -0
  185. package/dist/services/content-source-maps.js +108 -0
  186. package/dist/services/content-source-maps.js.map +1 -0
  187. package/dist/services/content-source-maps.mjs +106 -0
  188. package/dist/services/content-source-maps.mjs.map +1 -0
  189. package/dist/services/core-store.js.map +1 -1
  190. package/dist/services/core-store.mjs.map +1 -1
  191. package/dist/services/document-service/components.d.ts +31 -1
  192. package/dist/services/document-service/components.d.ts.map +1 -1
  193. package/dist/services/document-service/components.js +109 -0
  194. package/dist/services/document-service/components.js.map +1 -1
  195. package/dist/services/document-service/components.mjs +107 -1
  196. package/dist/services/document-service/components.mjs.map +1 -1
  197. package/dist/services/document-service/first-published-at.d.ts +7 -0
  198. package/dist/services/document-service/first-published-at.d.ts.map +1 -0
  199. package/dist/services/document-service/first-published-at.js +31 -0
  200. package/dist/services/document-service/first-published-at.js.map +1 -0
  201. package/dist/services/document-service/first-published-at.mjs +28 -0
  202. package/dist/services/document-service/first-published-at.mjs.map +1 -0
  203. package/dist/services/document-service/repository.d.ts.map +1 -1
  204. package/dist/services/document-service/repository.js +12 -5
  205. package/dist/services/document-service/repository.js.map +1 -1
  206. package/dist/services/document-service/repository.mjs +13 -6
  207. package/dist/services/document-service/repository.mjs.map +1 -1
  208. package/dist/services/document-service/transform/fields.js.map +1 -1
  209. package/dist/services/document-service/transform/fields.mjs.map +1 -1
  210. package/dist/services/document-service/transform/id-map.js.map +1 -1
  211. package/dist/services/document-service/transform/id-map.mjs.map +1 -1
  212. package/dist/services/document-service/utils/clean-component-join-table.d.ts +7 -0
  213. package/dist/services/document-service/utils/clean-component-join-table.d.ts.map +1 -0
  214. package/dist/services/document-service/utils/clean-component-join-table.js +145 -0
  215. package/dist/services/document-service/utils/clean-component-join-table.js.map +1 -0
  216. package/dist/services/document-service/utils/clean-component-join-table.mjs +143 -0
  217. package/dist/services/document-service/utils/clean-component-join-table.mjs.map +1 -0
  218. package/dist/services/document-service/utils/unidirectional-relations.d.ts +19 -2
  219. package/dist/services/document-service/utils/unidirectional-relations.d.ts.map +1 -1
  220. package/dist/services/document-service/utils/unidirectional-relations.js +21 -6
  221. package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -1
  222. package/dist/services/document-service/utils/unidirectional-relations.mjs +21 -6
  223. package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -1
  224. package/dist/services/entity-service/index.js.map +1 -1
  225. package/dist/services/entity-service/index.mjs.map +1 -1
  226. package/dist/services/entity-validator/blocks-validator.js.map +1 -1
  227. package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
  228. package/dist/services/entity-validator/index.js.map +1 -1
  229. package/dist/services/entity-validator/index.mjs.map +1 -1
  230. package/dist/services/metrics/index.d.ts +1 -1
  231. package/dist/services/metrics/index.d.ts.map +1 -1
  232. package/dist/services/metrics/index.js +11 -9
  233. package/dist/services/metrics/index.js.map +1 -1
  234. package/dist/services/metrics/index.mjs +11 -9
  235. package/dist/services/metrics/index.mjs.map +1 -1
  236. package/dist/services/metrics/middleware.d.ts +2 -1
  237. package/dist/services/metrics/middleware.d.ts.map +1 -1
  238. package/dist/services/metrics/middleware.js +2 -2
  239. package/dist/services/metrics/middleware.js.map +1 -1
  240. package/dist/services/metrics/middleware.mjs +2 -2
  241. package/dist/services/metrics/middleware.mjs.map +1 -1
  242. package/dist/services/metrics/sender.d.ts.map +1 -1
  243. package/dist/services/metrics/sender.js +4 -3
  244. package/dist/services/metrics/sender.js.map +1 -1
  245. package/dist/services/metrics/sender.mjs +4 -3
  246. package/dist/services/metrics/sender.mjs.map +1 -1
  247. package/dist/services/server/compose-endpoint.js.map +1 -1
  248. package/dist/services/server/compose-endpoint.mjs.map +1 -1
  249. package/dist/services/server/index.js.map +1 -1
  250. package/dist/services/server/index.mjs.map +1 -1
  251. package/dist/services/server/middleware.js.map +1 -1
  252. package/dist/services/server/middleware.mjs.map +1 -1
  253. package/dist/services/server/register-routes.js +22 -2
  254. package/dist/services/server/register-routes.js.map +1 -1
  255. package/dist/services/server/register-routes.mjs +22 -2
  256. package/dist/services/server/register-routes.mjs.map +1 -1
  257. package/dist/services/server/routing.d.ts +10 -0
  258. package/dist/services/server/routing.d.ts.map +1 -1
  259. package/dist/services/server/routing.js +7 -1
  260. package/dist/services/server/routing.js.map +1 -1
  261. package/dist/services/server/routing.mjs +7 -1
  262. package/dist/services/server/routing.mjs.map +1 -1
  263. package/dist/services/session-manager.d.ts +167 -0
  264. package/dist/services/session-manager.d.ts.map +1 -0
  265. package/dist/services/session-manager.js +529 -0
  266. package/dist/services/session-manager.js.map +1 -0
  267. package/dist/services/session-manager.mjs +526 -0
  268. package/dist/services/session-manager.mjs.map +1 -0
  269. package/dist/services/webhook-runner.js.map +1 -1
  270. package/dist/services/webhook-runner.mjs.map +1 -1
  271. package/dist/services/worker-queue.js.map +1 -1
  272. package/dist/services/worker-queue.mjs.map +1 -1
  273. package/dist/utils/fetch.js.map +1 -1
  274. package/dist/utils/fetch.mjs.map +1 -1
  275. package/dist/utils/filepath-to-prop-path.js.map +1 -1
  276. package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
  277. package/dist/utils/load-config-file.js.map +1 -1
  278. package/dist/utils/load-config-file.mjs.map +1 -1
  279. package/dist/utils/startup-logger.js.map +1 -1
  280. package/dist/utils/startup-logger.mjs.map +1 -1
  281. package/package.json +19 -16
@@ -23,6 +23,42 @@ const defaults = {
23
23
  ],
24
24
  keepHeadersOnError: false
25
25
  };
26
+ /**
27
+ * Determines if a request origin is allowed based on the configured origin list
28
+ * @param requestOrigin - The origin from the request header
29
+ * @param configuredOrigin - The origin configuration (string, array, or function)
30
+ * @param ctx - The Koa context (for function-based origin)
31
+ * @returns The allowed origin string or empty string if blocked
32
+ */ const matchOrigin = async (requestOrigin, configuredOrigin, ctx)=>{
33
+ if (!requestOrigin) {
34
+ return '*';
35
+ }
36
+ let originList;
37
+ if (typeof configuredOrigin === 'function') {
38
+ originList = await configuredOrigin(ctx);
39
+ } else {
40
+ originList = configuredOrigin;
41
+ }
42
+ // Normalize originList into an array
43
+ let normalizedOrigins;
44
+ if (Array.isArray(originList)) {
45
+ normalizedOrigins = originList;
46
+ } else if (originList === undefined || originList === null) {
47
+ // Handle undefined/null - treat as wildcard
48
+ normalizedOrigins = [
49
+ '*'
50
+ ];
51
+ } else {
52
+ // Handle comma-separated string of origins
53
+ normalizedOrigins = originList.split(',').map((origin)=>origin.trim());
54
+ }
55
+ // Check if wildcard is in the normalized origins
56
+ if (normalizedOrigins.includes('*')) {
57
+ return requestOrigin;
58
+ }
59
+ // Check if request origin is in the normalized origins
60
+ return normalizedOrigins.includes(requestOrigin) ? requestOrigin : '';
61
+ };
26
62
  const cors = (config)=>{
27
63
  const { origin, expose, maxAge, credentials, methods, headers, keepHeadersOnError } = {
28
64
  ...defaults,
@@ -33,23 +69,8 @@ const cors = (config)=>{
33
69
  }
34
70
  return koaCors({
35
71
  async origin (ctx) {
36
- if (!ctx.get('Origin')) {
37
- return '*';
38
- }
39
- let originList;
40
- if (typeof origin === 'function') {
41
- originList = await origin(ctx);
42
- } else {
43
- originList = origin;
44
- }
45
- if (Array.isArray(originList)) {
46
- return originList.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';
47
- }
48
- const parsedOrigin = originList.split(',').map((origin)=>origin.trim());
49
- if (parsedOrigin.length > 1) {
50
- return parsedOrigin.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';
51
- }
52
- return originList;
72
+ const requestOrigin = ctx.get('Origin');
73
+ return matchOrigin(requestOrigin, origin, ctx);
53
74
  },
54
75
  exposeHeaders: expose,
55
76
  maxAge,
@@ -61,4 +82,5 @@ const cors = (config)=>{
61
82
  };
62
83
 
63
84
  exports.cors = cors;
85
+ exports.matchOrigin = matchOrigin;
64
86
  //# sourceMappingURL=cors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cors.js","sources":["../../src/middlewares/cors.ts"],"sourcesContent":["import koaCors from '@koa/cors';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = {\n enabled?: boolean;\n origin: string | string[] | ((ctx: any) => string | string[]);\n expose?: string | string[];\n maxAge?: number;\n credentials?: boolean;\n methods?: string | string[];\n headers?: string | string[];\n keepHeadersOnError?: boolean;\n};\n\nconst defaults: Config = {\n origin: '*',\n maxAge: 31536000,\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],\n headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],\n keepHeadersOnError: false,\n};\n\nexport const cors: Core.MiddlewareFactory<Config> = (config) => {\n const { origin, expose, maxAge, credentials, methods, headers, keepHeadersOnError } = {\n ...defaults,\n ...config,\n };\n\n if (config.enabled !== undefined) {\n strapi.log.warn(\n 'The strapi::cors middleware no longer supports the `enabled` option. Using it' +\n ' to conditionally enable CORS might cause an insecure default. To disable strapi::cors, remove it from' +\n ' the exported array in config/middleware.js'\n );\n }\n\n return koaCors({\n async origin(ctx) {\n if (!ctx.get('Origin')) {\n return '*';\n }\n\n let originList: string | string[];\n\n if (typeof origin === 'function') {\n originList = await origin(ctx);\n } else {\n originList = origin;\n }\n\n if (Array.isArray(originList)) {\n return originList.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';\n }\n\n const parsedOrigin = originList.split(',').map((origin) => origin.trim());\n if (parsedOrigin.length > 1) {\n return parsedOrigin.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';\n }\n\n return originList;\n },\n exposeHeaders: expose,\n maxAge,\n credentials,\n allowMethods: methods,\n allowHeaders: headers,\n keepHeadersOnError,\n });\n};\n"],"names":["defaults","origin","maxAge","credentials","methods","headers","keepHeadersOnError","cors","config","expose","enabled","undefined","strapi","log","warn","koaCors","ctx","get","originList","Array","isArray","includes","parsedOrigin","split","map","trim","length","exposeHeaders","allowMethods","allowHeaders"],"mappings":";;;;AAeA,MAAMA,QAAmB,GAAA;IACvBC,MAAQ,EAAA,GAAA;IACRC,MAAQ,EAAA,QAAA;IACRC,WAAa,EAAA,IAAA;IACbC,OAAS,EAAA;AAAC,QAAA,KAAA;AAAO,QAAA,MAAA;AAAQ,QAAA,KAAA;AAAO,QAA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A,CAAOwB,IAAI,EAAA,CAAA;YACtE,IAAIH,YAAAA,CAAaI,MAAM,GAAG,CAAG,EAAA;gBAC3B,OAAOJ,YAAAA,CAAaD,QAAQ,CAACL,GAAIC,CAAAA,GAAG,CAAC,QAAaD,CAAAA,CAAAA,GAAAA,GAAAA,CAAIC,GAAG,CAAC,QAAY,CAAA,GAAA,EAAA;AACxE;YAEA,OAAOC,UAAAA;AACT,SAAA;QACAS,aAAelB,EAAAA,MAAAA;AACfP,QAAAA,MAAAA;AACAC,QAAAA,WAAAA;QACAyB,YAAcxB,EAAAA,OAAAA;QACdyB,YAAcxB,EAAAA,OAAAA;AACdC,QAAAA;AACF,KAAA,CAAA;AACF;;;;"}
1
+ {"version":3,"file":"cors.js","sources":["../../src/middlewares/cors.ts"],"sourcesContent":["import koaCors from '@koa/cors';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = {\n enabled?: boolean;\n origin: string | string[] | ((ctx: any) => string | string[] | Promise<string | string[]>);\n expose?: string | string[];\n maxAge?: number;\n credentials?: boolean;\n methods?: string | string[];\n headers?: string | string[];\n keepHeadersOnError?: boolean;\n};\n\nconst defaults: Config = {\n origin: '*',\n maxAge: 31536000,\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],\n headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],\n keepHeadersOnError: false,\n};\n\n/**\n * Determines if a request origin is allowed based on the configured origin list\n * @param requestOrigin - The origin from the request header\n * @param configuredOrigin - The origin configuration (string, array, or function)\n * @param ctx - The Koa context (for function-based origin)\n * @returns The allowed origin string or empty string if blocked\n */\nexport const matchOrigin = async (\n requestOrigin: string | undefined,\n configuredOrigin:\n | string\n | string[]\n | ((ctx: any) => string | string[] | Promise<string | string[]>),\n ctx?: any\n): Promise<string> => {\n if (!requestOrigin) {\n return '*';\n }\n\n let originList: string | string[];\n\n if (typeof configuredOrigin === 'function') {\n originList = await configuredOrigin(ctx);\n } else {\n originList = configuredOrigin;\n }\n\n // Normalize originList into an array\n let normalizedOrigins: string[];\n if (Array.isArray(originList)) {\n normalizedOrigins = originList;\n } else if (originList === undefined || originList === null) {\n // Handle undefined/null - treat as wildcard\n normalizedOrigins = ['*'];\n } else {\n // Handle comma-separated string of origins\n normalizedOrigins = originList.split(',').map((origin) => origin.trim());\n }\n\n // Check if wildcard is in the normalized origins\n if (normalizedOrigins.includes('*')) {\n return requestOrigin;\n }\n\n // Check if request origin is in the normalized origins\n return normalizedOrigins.includes(requestOrigin) ? requestOrigin : '';\n};\n\nexport const cors: Core.MiddlewareFactory<Config> = (config) => {\n const { origin, expose, maxAge, credentials, methods, headers, keepHeadersOnError } = {\n ...defaults,\n ...config,\n };\n\n if (config.enabled !== undefined) {\n strapi.log.warn(\n 'The strapi::cors middleware no longer supports the `enabled` option. Using it' +\n ' to conditionally enable CORS might cause an insecure default. To disable strapi::cors, remove it from' +\n ' the exported array in config/middleware.js'\n );\n }\n\n return koaCors({\n async origin(ctx) {\n const requestOrigin = ctx.get('Origin');\n return matchOrigin(requestOrigin, origin, ctx);\n },\n exposeHeaders: expose,\n maxAge,\n credentials,\n allowMethods: methods,\n allowHeaders: headers,\n keepHeadersOnError,\n });\n};\n"],"names":["defaults","origin","maxAge","credentials","methods","headers","keepHeadersOnError","matchOrigin","requestOrigin","configuredOrigin","ctx","originList","normalizedOrigins","Array","isArray","undefined","split","map","trim","includes","cors","config","expose","enabled","strapi","log","warn","koaCors","get","exposeHeaders","allowMethods","allowHeaders"],"mappings":";;;;AAeA,MAAMA,QAAmB,GAAA;IACvBC,MAAQ,EAAA,GAAA;IACRC,MAAQ,EAAA,QAAA;IACRC,WAAa,EAAA,IAAA;IACbC,OAAS,EAAA;AAAC,QAAA,KAAA;AAAO,QAAA,MAAA;AAAQ,QAAA,KAAA;AAAO,QAAA,OAAA;AAAS,QAAA,QAAA;AAAU,QAAA,MAAA;AAAQ,QAAA;AAAU,KAAA;IACrEC,OAAS,EAAA;AAAC,Q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KAAA;IAEA,IAAIA,MAAAA,CAAOE,OAAO,KAAKR,SAAW,EAAA;AAChCS,QAAAA,MAAAA,CAAOC,GAAG,CAACC,IAAI,CACb,kFACE,wGACA,GAAA,6CAAA,CAAA;AAEN;AAEA,IAAA,OAAOC,OAAQ,CAAA;AACb,QAAA,MAAM1B,QAAOS,GAAG,EAAA;YACd,MAAMF,aAAAA,GAAgBE,GAAIkB,CAAAA,GAAG,CAAC,QAAA,CAAA;YAC9B,OAAOrB,WAAAA,CAAYC,eAAeP,MAAQS,EAAAA,GAAAA,CAAAA;AAC5C,SAAA;QACAmB,aAAeP,EAAAA,MAAAA;AACfpB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA;QACA2B,YAAc1B,EAAAA,OAAAA;QACd2B,YAAc1B,EAAAA,OAAAA;AACdC,QAAAA;AACF,KAAA,CAAA;AACF;;;;;"}
@@ -21,6 +21,42 @@ const defaults = {
21
21
  ],
22
22
  keepHeadersOnError: false
23
23
  };
24
+ /**
25
+ * Determines if a request origin is allowed based on the configured origin list
26
+ * @param requestOrigin - The origin from the request header
27
+ * @param configuredOrigin - The origin configuration (string, array, or function)
28
+ * @param ctx - The Koa context (for function-based origin)
29
+ * @returns The allowed origin string or empty string if blocked
30
+ */ const matchOrigin = async (requestOrigin, configuredOrigin, ctx)=>{
31
+ if (!requestOrigin) {
32
+ return '*';
33
+ }
34
+ let originList;
35
+ if (typeof configuredOrigin === 'function') {
36
+ originList = await configuredOrigin(ctx);
37
+ } else {
38
+ originList = configuredOrigin;
39
+ }
40
+ // Normalize originList into an array
41
+ let normalizedOrigins;
42
+ if (Array.isArray(originList)) {
43
+ normalizedOrigins = originList;
44
+ } else if (originList === undefined || originList === null) {
45
+ // Handle undefined/null - treat as wildcard
46
+ normalizedOrigins = [
47
+ '*'
48
+ ];
49
+ } else {
50
+ // Handle comma-separated string of origins
51
+ normalizedOrigins = originList.split(',').map((origin)=>origin.trim());
52
+ }
53
+ // Check if wildcard is in the normalized origins
54
+ if (normalizedOrigins.includes('*')) {
55
+ return requestOrigin;
56
+ }
57
+ // Check if request origin is in the normalized origins
58
+ return normalizedOrigins.includes(requestOrigin) ? requestOrigin : '';
59
+ };
24
60
  const cors = (config)=>{
25
61
  const { origin, expose, maxAge, credentials, methods, headers, keepHeadersOnError } = {
26
62
  ...defaults,
@@ -31,23 +67,8 @@ const cors = (config)=>{
31
67
  }
32
68
  return koaCors({
33
69
  async origin (ctx) {
34
- if (!ctx.get('Origin')) {
35
- return '*';
36
- }
37
- let originList;
38
- if (typeof origin === 'function') {
39
- originList = await origin(ctx);
40
- } else {
41
- originList = origin;
42
- }
43
- if (Array.isArray(originList)) {
44
- return originList.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';
45
- }
46
- const parsedOrigin = originList.split(',').map((origin)=>origin.trim());
47
- if (parsedOrigin.length > 1) {
48
- return parsedOrigin.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';
49
- }
50
- return originList;
70
+ const requestOrigin = ctx.get('Origin');
71
+ return matchOrigin(requestOrigin, origin, ctx);
51
72
  },
52
73
  exposeHeaders: expose,
53
74
  maxAge,
@@ -58,5 +79,5 @@ const cors = (config)=>{
58
79
  });
59
80
  };
60
81
 
61
- export { cors };
82
+ export { cors, matchOrigin };
62
83
  //# sourceMappingURL=cors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cors.mjs","sources":["../../src/middlewares/cors.ts"],"sourcesContent":["import koaCors from '@koa/cors';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = {\n enabled?: boolean;\n origin: string | string[] | ((ctx: any) => string | string[]);\n expose?: string | string[];\n maxAge?: number;\n credentials?: boolean;\n methods?: string | string[];\n headers?: string | string[];\n keepHeadersOnError?: boolean;\n};\n\nconst defaults: Config = {\n origin: '*',\n maxAge: 31536000,\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],\n headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],\n keepHeadersOnError: false,\n};\n\nexport const cors: Core.MiddlewareFactory<Config> = (config) => {\n const { origin, expose, maxAge, credentials, methods, headers, keepHeadersOnError } = {\n ...defaults,\n ...config,\n };\n\n if (config.enabled !== undefined) {\n strapi.log.warn(\n 'The strapi::cors middleware no longer supports the `enabled` option. Using it' +\n ' to conditionally enable CORS might cause an insecure default. To disable strapi::cors, remove it from' +\n ' the exported array in config/middleware.js'\n );\n }\n\n return koaCors({\n async origin(ctx) {\n if (!ctx.get('Origin')) {\n return '*';\n }\n\n let originList: string | string[];\n\n if (typeof origin === 'function') {\n originList = await origin(ctx);\n } else {\n originList = origin;\n }\n\n if (Array.isArray(originList)) {\n return originList.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';\n }\n\n const parsedOrigin = originList.split(',').map((origin) => origin.trim());\n if (parsedOrigin.length > 1) {\n return parsedOrigin.includes(ctx.get('Origin')) ? ctx.get('Origin') : '';\n }\n\n return originList;\n },\n exposeHeaders: expose,\n maxAge,\n credentials,\n allowMethods: methods,\n allowHeaders: headers,\n keepHeadersOnError,\n });\n};\n"],"names":["defaults","origin","maxAge","credentials","methods","headers","keepHeadersOnError","cors","config","expose","enabled","undefined","strapi","log","warn","koaCors","ctx","get","originList","Array","isArray","includes","parsedOrigin","split","map","trim","length","exposeHeaders","allowMethods","allowHeaders"],"mappings":";;AAeA,MAAMA,QAAmB,GAAA;IACvBC,MAAQ,EAAA,GAAA;IACRC,MAAQ,EAAA,QAAA;IACRC,WAAa,EAAA,IAAA;IACbC,OAAS,EAAA;AAAC,QAAA,KAAA;AAAO,QAAA,MAAA;AAAQ,QAAA,KAAA;AAAO,QAAA,OAAA;AAAS,QAAA,QAAA;AAAU,QAAA,MAAA;AAAQ,QAAA;AAAU,KAAA;IACrEC,OAAS,EAAA;AAAC,QAAA,cAAA;AAAgB,QAAA,eAAA;AAAiB,QAAA,QAAA;AAAU,QAAA;AAAS,KAAA;IAC9DC,kBAAoB,EAAA;AACtB,CAAA;AAEO,MAAMC,OA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AAA,EAAA;AACxE;YAEA,OAAOC,UAAAA;AACT,SAAA;QACAS,aAAelB,EAAAA,MAAAA;AACfP,QAAAA,MAAAA;AACAC,QAAAA,WAAAA;QACAyB,YAAcxB,EAAAA,OAAAA;QACdyB,YAAcxB,EAAAA,OAAAA;AACdC,QAAAA;AACF,KAAA,CAAA;AACF;;;;"}
1
+ {"version":3,"file":"cors.mjs","sources":["../../src/middlewares/cors.ts"],"sourcesContent":["import koaCors from '@koa/cors';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = {\n enabled?: boolean;\n origin: string | string[] | ((ctx: any) => string | string[] | Promise<string | string[]>);\n expose?: string | string[];\n maxAge?: number;\n credentials?: boolean;\n methods?: string | string[];\n headers?: string | string[];\n keepHeadersOnError?: boolean;\n};\n\nconst defaults: Config = {\n origin: '*',\n maxAge: 31536000,\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],\n headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],\n keepHeadersOnError: false,\n};\n\n/**\n * Determines if a request origin is allowed based on the configured origin list\n * @param requestOrigin - The origin from the request header\n * @param configuredOrigin - The origin configuration (string, array, or function)\n * @param ctx - The Koa context (for function-based origin)\n * @returns The allowed origin string or empty string if blocked\n */\nexport const matchOrigin = async (\n requestOrigin: string | undefined,\n configuredOrigin:\n | string\n | string[]\n | ((ctx: any) => string | string[] | Promise<string | string[]>),\n ctx?: any\n): Promise<string> => {\n if (!requestOrigin) {\n return '*';\n }\n\n let originList: string | string[];\n\n if (typeof configuredOrigin === 'function') {\n originList = await configuredOrigin(ctx);\n } else {\n originList = configuredOrigin;\n }\n\n // Normalize originList into an array\n let normalizedOrigins: string[];\n if (Array.isArray(originList)) {\n normalizedOrigins = originList;\n } else if (originList === undefined || originList === null) {\n // Handle undefined/null - treat as wildcard\n normalizedOrigins = ['*'];\n } else {\n // Handle comma-separated string of origins\n normalizedOrigins = originList.split(',').map((origin) => origin.trim());\n }\n\n // Check if wildcard is in the normalized origins\n if (normalizedOrigins.includes('*')) {\n return requestOrigin;\n }\n\n // Check if request origin is in the normalized origins\n return normalizedOrigins.includes(requestOrigin) ? requestOrigin : '';\n};\n\nexport const cors: Core.MiddlewareFactory<Config> = (config) => {\n const { origin, expose, maxAge, credentials, methods, headers, keepHeadersOnError } = {\n ...defaults,\n ...config,\n };\n\n if (config.enabled !== undefined) {\n strapi.log.warn(\n 'The strapi::cors middleware no longer supports the `enabled` option. Using it' +\n ' to conditionally enable CORS might cause an insecure default. To disable strapi::cors, remove it from' +\n ' the exported array in config/middleware.js'\n );\n }\n\n return koaCors({\n async origin(ctx) {\n const requestOrigin = ctx.get('Origin');\n return matchOrigin(requestOrigin, origin, ctx);\n },\n exposeHeaders: expose,\n maxAge,\n credentials,\n allowMethods: methods,\n allowHeaders: headers,\n keepHeadersOnError,\n });\n};\n"],"names":["defaults","origin","maxAge","credentials","methods","headers","keepHeadersOnError","matchOrigin","requestOrigin","configuredOrigin","ctx","originList","normalizedOrigins","Array","isArray","undefined","split","map","trim","includes","cors","config","expose","enabled","strapi","log","warn","koaCors","get","exposeHeaders","allowMethods","allowHeaders"],"mappings":";;AAeA,MAAMA,QAAmB,GAAA;IACvBC,MAAQ,EAAA,GAAA;IACRC,MAAQ,EAAA,QAAA;IACRC,WAAa,EAAA,IAAA;IACbC,OAAS,EAAA;AAAC,QAAA,KAAA;AAAO,QAAA,MAAA;AAAQ,QAAA,KAAA;AAAO,QAAA,OAAA;AAAS,QAAA,QAAA;AAAU,QAAA,MAAA;AAAQ,QAAA;AAAU,KAAA;IACrEC,OAAS,EAAA;AAAC,QAAA,cAAA;AAAgB,QAAA,eAAA;AAAiB,QAAA,QAAA;AAAU,QAAA;AAAS,KAAA;IAC9DC,kBAAoB,EAAA;AACtB,CAAA;AAEA;;;;;;AAMC,IACM,MAAMC,WAAc,GAAA,OACzBC,eACAC,gBAIAC,EAAAA,GAAAA,GAAAA;AAEA,IAAA,IAAI,CAACF,aA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ACd,MAAMF,aAAAA,GAAgBE,GAAIkB,CAAAA,GAAG,CAAC,QAAA,CAAA;YAC9B,OAAOrB,WAAAA,CAAYC,eAAeP,MAAQS,EAAAA,GAAAA,CAAAA;AAC5C,SAAA;QACAmB,aAAeP,EAAAA,MAAAA;AACfpB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA;QACA2B,YAAc1B,EAAAA,OAAAA;QACd2B,YAAc1B,EAAAA,OAAAA;AACdC,QAAAA;AACF,KAAA,CAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","sources":["../../src/middlewares/logger.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const logger: Core.MiddlewareFactory = (_, { strapi }) => {\n return async (ctx, next) => {\n const start = Date.now();\n await next();\n const delta = Math.ceil(Date.now() - start);\n\n strapi.log.http(`${ctx.method} ${ctx.url} (${delta} ms) ${ctx.status}`);\n };\n};\n"],"names":["logger","_","strapi","ctx","next","start","Date","now","delta","Math","ceil","log","http","method","url","status"],"mappings":";;MAEaA,MAAiC,GAAA,CAACC,CAAG,EAAA,EAAEC,MAAM,EAAE,GAAA;AAC1D,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QACtB,MAAMH,IAAAA,EAAAA;AACN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;QAErCH,MAAOS,CAAAA,GAAG,CAACC,IAAI,CAAC,CAAC,EAAET,GAAAA,CAAIU,MAAM,CAAC,CAAC,EAAEV,IAAIW,GAAG,CAAC,EAAE,EAAEN,KAAAA,CAAM,KAAK,EAAEL,GAAAA,CAAIY,MAAM,CAAC,CAAC,CAAA;AACxE,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"logger.js","sources":["../../src/middlewares/logger.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const logger: Core.MiddlewareFactory = (_, { strapi }) => {\n return async (ctx, next) => {\n const start = Date.now();\n await next();\n const delta = Math.ceil(Date.now() - start);\n\n strapi.log.http(`${ctx.method} ${ctx.url} (${delta} ms) ${ctx.status}`);\n };\n};\n"],"names":["logger","_","strapi","ctx","next","start","Date","now","delta","Math","ceil","log","http","method","url","status"],"mappings":";;MAEaA,MAAiC,GAAA,CAACC,CAAG,EAAA,EAAEC,MAAM,EAAE,GAAA;AAC1D,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QACtB,MAAMH,IAAAA,EAAAA;AACN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;QAErCH,MAAOS,CAAAA,GAAG,CAACC,IAAI,CAAC,GAAGT,GAAIU,CAAAA,MAAM,CAAC,CAAC,EAAEV,IAAIW,GAAG,CAAC,EAAE,EAAEN,KAAAA,CAAM,KAAK,EAAEL,GAAAA,CAAIY,MAAM,CAAE,CAAA,CAAA;AACxE,KAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","sources":["../../src/middlewares/logger.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const logger: Core.MiddlewareFactory = (_, { strapi }) => {\n return async (ctx, next) => {\n const start = Date.now();\n await next();\n const delta = Math.ceil(Date.now() - start);\n\n strapi.log.http(`${ctx.method} ${ctx.url} (${delta} ms) ${ctx.status}`);\n };\n};\n"],"names":["logger","_","strapi","ctx","next","start","Date","now","delta","Math","ceil","log","http","method","url","status"],"mappings":"MAEaA,MAAiC,GAAA,CAACC,CAAG,EAAA,EAAEC,MAAM,EAAE,GAAA;AAC1D,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QACtB,MAAMH,IAAAA,EAAAA;AACN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;QAErCH,MAAOS,CAAAA,GAAG,CAACC,IAAI,CAAC,CAAC,EAAET,GAAAA,CAAIU,MAAM,CAAC,CAAC,EAAEV,IAAIW,GAAG,CAAC,EAAE,EAAEN,KAAAA,CAAM,KAAK,EAAEL,GAAAA,CAAIY,MAAM,CAAC,CAAC,CAAA;AACxE,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"logger.mjs","sources":["../../src/middlewares/logger.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const logger: Core.MiddlewareFactory = (_, { strapi }) => {\n return async (ctx, next) => {\n const start = Date.now();\n await next();\n const delta = Math.ceil(Date.now() - start);\n\n strapi.log.http(`${ctx.method} ${ctx.url} (${delta} ms) ${ctx.status}`);\n };\n};\n"],"names":["logger","_","strapi","ctx","next","start","Date","now","delta","Math","ceil","log","http","method","url","status"],"mappings":"MAEaA,MAAiC,GAAA,CAACC,CAAG,EAAA,EAAEC,MAAM,EAAE,GAAA;AAC1D,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QACtB,MAAMH,IAAAA,EAAAA;AACN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;QAErCH,MAAOS,CAAAA,GAAG,CAACC,IAAI,CAAC,GAAGT,GAAIU,CAAAA,MAAM,CAAC,CAAC,EAAEV,IAAIW,GAAG,CAAC,EAAE,EAAEN,KAAAA,CAAM,KAAK,EAAEL,GAAAA,CAAIY,MAAM,CAAE,CAAA,CAAA;AACxE,KAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"response-time.js","sources":["../../src/middlewares/response-time.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const responseTime: Core.MiddlewareFactory = () => {\n return async (ctx, next) => {\n const start = Date.now();\n\n await next();\n\n const delta = Math.ceil(Date.now() - start);\n ctx.set('X-Response-Time', `${delta}ms`);\n };\n};\n"],"names":["responseTime","ctx","next","start","Date","now","delta","Math","ceil","set"],"mappings":";;MAEaA,YAAuC,GAAA,IAAA;AAClD,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QAEtB,MAAMH,IAAAA,EAAAA;AAEN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;AACrCF,QAAAA,GAAAA,CAAIQ,GAAG,CAAC,iBAAA,EAAmB,CAAC,EAAEH,KAAAA,CAAM,EAAE,CAAC,CAAA;AACzC,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"response-time.js","sources":["../../src/middlewares/response-time.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const responseTime: Core.MiddlewareFactory = () => {\n return async (ctx, next) => {\n const start = Date.now();\n\n await next();\n\n const delta = Math.ceil(Date.now() - start);\n ctx.set('X-Response-Time', `${delta}ms`);\n };\n};\n"],"names":["responseTime","ctx","next","start","Date","now","delta","Math","ceil","set"],"mappings":";;MAEaA,YAAuC,GAAA,IAAA;AAClD,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QAEtB,MAAMH,IAAAA,EAAAA;AAEN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;AACrCF,QAAAA,GAAAA,CAAIQ,GAAG,CAAC,iBAAA,EAAmB,CAAGH,EAAAA,KAAAA,CAAM,EAAE,CAAC,CAAA;AACzC,KAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"response-time.mjs","sources":["../../src/middlewares/response-time.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const responseTime: Core.MiddlewareFactory = () => {\n return async (ctx, next) => {\n const start = Date.now();\n\n await next();\n\n const delta = Math.ceil(Date.now() - start);\n ctx.set('X-Response-Time', `${delta}ms`);\n };\n};\n"],"names":["responseTime","ctx","next","start","Date","now","delta","Math","ceil","set"],"mappings":"MAEaA,YAAuC,GAAA,IAAA;AAClD,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QAEtB,MAAMH,IAAAA,EAAAA;AAEN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;AACrCF,QAAAA,GAAAA,CAAIQ,GAAG,CAAC,iBAAA,EAAmB,CAAC,EAAEH,KAAAA,CAAM,EAAE,CAAC,CAAA;AACzC,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"response-time.mjs","sources":["../../src/middlewares/response-time.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const responseTime: Core.MiddlewareFactory = () => {\n return async (ctx, next) => {\n const start = Date.now();\n\n await next();\n\n const delta = Math.ceil(Date.now() - start);\n ctx.set('X-Response-Time', `${delta}ms`);\n };\n};\n"],"names":["responseTime","ctx","next","start","Date","now","delta","Math","ceil","set"],"mappings":"MAEaA,YAAuC,GAAA,IAAA;AAClD,IAAA,OAAO,OAAOC,GAAKC,EAAAA,IAAAA,GAAAA;QACjB,MAAMC,KAAAA,GAAQC,KAAKC,GAAG,EAAA;QAEtB,MAAMH,IAAAA,EAAAA;AAEN,QAAA,MAAMI,QAAQC,IAAKC,CAAAA,IAAI,CAACJ,IAAAA,CAAKC,GAAG,EAAKF,GAAAA,KAAAA,CAAAA;AACrCF,QAAAA,GAAAA,CAAIQ,GAAG,CAAC,iBAAA,EAAmB,CAAGH,EAAAA,KAAAA,CAAM,EAAE,CAAC,CAAA;AACzC,KAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../../src/middlewares/security.ts"],"names":[],"mappings":"AACA,OAAe,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,MAAM,MAAM,MAAM,GAAG,WAAW,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAkC3D,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAmEjD,CAAC"}
1
+ {"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../../src/middlewares/security.ts"],"names":[],"mappings":"AACA,OAAe,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAG/C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,MAAM,MAAM,MAAM,GAAG,WAAW,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAgC3D,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAkEjD,CAAC"}
@@ -2,6 +2,7 @@
2
2
 
3
3
  var fp = require('lodash/fp');
4
4
  var helmet = require('koa-helmet');
5
+ var strapiUtils = require('@strapi/utils');
5
6
 
6
7
  const defaults = {
7
8
  crossOriginEmbedderPolicy: false,
@@ -11,21 +12,7 @@ const defaults = {
11
12
  contentSecurityPolicy: {
12
13
  useDefaults: true,
13
14
  directives: {
14
- 'connect-src': [
15
- "'self'",
16
- 'https:'
17
- ],
18
- 'img-src': [
19
- "'self'",
20
- 'data:',
21
- 'blob:',
22
- 'https://market-assets.strapi.io'
23
- ],
24
- 'media-src': [
25
- "'self'",
26
- 'data:',
27
- 'blob:'
28
- ],
15
+ ...strapiUtils.CSP_DEFAULTS,
29
16
  upgradeInsecureRequests: null
30
17
  }
31
18
  },
@@ -1 +1 @@
1
- {"version":3,"file":"security.js","sources":["../../src/middlewares/security.ts"],"sourcesContent":["import { defaultsDeep, mergeWith } from 'lodash/fp';\nimport helmet, { KoaHelmet } from 'koa-helmet';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = NonNullable<Parameters<KoaHelmet>[0]>;\n\nconst defaults: Config = {\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n contentSecurityPolicy: {\n useDefaults: true,\n directives: {\n 'connect-src': [\"'self'\", 'https:'],\n 'img-src': [\"'self'\", 'data:', 'blob:', 'https://market-assets.strapi.io'],\n 'media-src': [\"'self'\", 'data:', 'blob:'],\n upgradeInsecureRequests: null,\n },\n },\n xssFilter: false,\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n },\n frameguard: {\n action: 'sameorigin',\n },\n};\n\nconst mergeConfig = (existingConfig: Config, newConfig: Config) => {\n return mergeWith(\n (obj, src) => (Array.isArray(obj) && Array.isArray(src) ? obj.concat(src) : undefined),\n existingConfig,\n newConfig\n );\n};\n\nexport const security: Core.MiddlewareFactory<Config> =\n (config, { strapi }) =>\n (ctx, next) => {\n let helmetConfig: Config = defaultsDeep(defaults, config);\n\n const specialPaths = ['/documentation'];\n\n const directives: {\n 'script-src': string[];\n 'img-src': string[];\n 'manifest-src': string[];\n 'frame-src': string[];\n } = {\n 'script-src': [\"'self'\", \"'unsafe-inline'\", 'cdn.jsdelivr.net'],\n 'img-src': [\"'self'\", 'data:', 'cdn.jsdelivr.net', 'strapi.io'],\n 'manifest-src': [],\n 'frame-src': [],\n };\n\n // if apollo graphql playground is enabled, add exceptions for it\n if (strapi.plugin('graphql')?.service('utils').playground.isEnabled()) {\n const { config: gqlConfig } = strapi.plugin('graphql');\n specialPaths.push(gqlConfig('endpoint'));\n\n directives['script-src'].push(`https: 'unsafe-inline'`);\n directives['img-src'].push(`'apollo-server-landing-page.cdn.apollographql.com'`);\n directives['manifest-src'].push(`'self'`);\n directives['manifest-src'].push('apollo-server-landing-page.cdn.apollographql.com');\n directives['frame-src'].push(`'self'`);\n directives['frame-src'].push('sandbox.embed.apollographql.com');\n }\n\n // TODO: we shouldn't combine playground exceptions with documentation for all routes, we should first check the path and then return exceptions specific to that\n if (ctx.method === 'GET' && specialPaths.some((str) => ctx.path.startsWith(str))) {\n helmetConfig = mergeConfig(helmetConfig, {\n crossOriginEmbedderPolicy: false, // TODO: only use this for graphql playground\n contentSecurityPolicy: {\n directives,\n },\n });\n }\n\n /**\n * These are for vite's watch mode so it can accurately\n * connect to the HMR websocket & reconnect on failure\n * or when the server restarts.\n *\n * It only applies in development, and only on GET requests\n * that are part of the admin route.\n */\n\n if (\n ['development', 'test'].includes(process.env.NODE_ENV ?? '') &&\n ctx.method === 'GET' &&\n ctx.path.startsWith(strapi.config.get('admin.path'))\n ) {\n helmetConfig = mergeConfig(helmetConfig, {\n contentSecurityPolicy: {\n directives: {\n 'script-src': [\"'self'\", \"'unsafe-inline'\"],\n 'connect-src': [\"'self'\", 'http:', 'https:', 'ws:'],\n },\n },\n });\n }\n\n return helmet(helmetConfig)(ctx, next);\n };\n"],"names":["defaults","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","originAgentCluster","contentSecurityPolicy","useDefaults","directives","upgradeInsecureRequests","xssFilter","hsts","maxAge","includeSubDomains","frameguard","action","mergeConfig","existingConfig","newConfig","mergeWith","obj","src","Array","isArray","concat","undefined","security","config","strapi","ctx","next","helmetConfig","defaultsDeep","specialPaths","plugin","service","playground","isEnabled","gqlConfig","push","method","some","str","path","startsWith","includes","process","env","NODE_ENV","get","helmet"],"mappings":";;;;;AAOA,MAAMA,QAAmB,GAAA;IACvBC,yBAA2B,EAAA,KAAA;IAC3BC,uBAAyB,EAAA,KAAA;IACzBC,yBAA2B,EAAA,KAA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;AAAC,YAAA,aAAA;AAAe,YAAA;SAAO,CAACqC,QAAQ,CAACC,OAAQC,CAAAA,GAAG,CAACC,QAAQ,IAAI,EACzDnB,CAAAA,IAAAA,GAAAA,CAAIW,MAAM,KAAK,SACfX,GAAIc,CAAAA,IAAI,CAACC,UAAU,CAAChB,OAAOD,MAAM,CAACsB,GAAG,CAAC,YACtC,CAAA,CAAA,EAAA;AACAlB,YAAAA,YAAAA,GAAef,YAAYe,YAAc,EAAA;gBACvCzB,qBAAuB,EAAA;oBACrBE,UAAY,EAAA;wBACV,YAAc,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA;AAAkB,yBAAA;wBAC3C,aAAe,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA,OAAA;AAAS,4BAAA,QAAA;AAAU,4BAAA;AAAM;AACrD;AACF;AACF,aAAA,CAAA;AACF;QAEA,OAAO0C,MAAAA,CAAOnB,cAAcF,GAAKC,EAAAA,IAAAA,CAAAA;;;;;"}
1
+ {"version":3,"file":"security.js","sources":["../../src/middlewares/security.ts"],"sourcesContent":["import { defaultsDeep, mergeWith } from 'lodash/fp';\nimport helmet, { KoaHelmet } from 'koa-helmet';\nimport { CSP_DEFAULTS } from '@strapi/utils';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = NonNullable<Parameters<KoaHelmet>[0]>;\n\nconst defaults: Config = {\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n contentSecurityPolicy: {\n useDefaults: true,\n directives: {\n ...CSP_DEFAULTS,\n upgradeInsecureRequests: null,\n },\n },\n xssFilter: false,\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n },\n frameguard: {\n action: 'sameorigin',\n },\n};\n\nconst mergeConfig = (existingConfig: Config, newConfig: Config) => {\n return mergeWith(\n (obj, src) => (Array.isArray(obj) && Array.isArray(src) ? obj.concat(src) : undefined),\n existingConfig,\n newConfig\n );\n};\n\nexport const security: Core.MiddlewareFactory<Config> =\n (config, { strapi }) =>\n (ctx, next) => {\n let helmetConfig: Config = defaultsDeep(defaults, config);\n const specialPaths = ['/documentation'];\n\n const directives: {\n 'script-src': string[];\n 'img-src': string[];\n 'manifest-src': string[];\n 'frame-src': string[];\n } = {\n 'script-src': [\"'self'\", \"'unsafe-inline'\", 'cdn.jsdelivr.net'],\n 'img-src': [\"'self'\", 'data:', 'cdn.jsdelivr.net', 'strapi.io'],\n 'manifest-src': [],\n 'frame-src': [],\n };\n\n // if apollo graphql playground is enabled, add exceptions for it\n if (strapi.plugin('graphql')?.service('utils').playground.isEnabled()) {\n const { config: gqlConfig } = strapi.plugin('graphql');\n specialPaths.push(gqlConfig('endpoint'));\n\n directives['script-src'].push(`https: 'unsafe-inline'`);\n directives['img-src'].push(`'apollo-server-landing-page.cdn.apollographql.com'`);\n directives['manifest-src'].push(`'self'`);\n directives['manifest-src'].push('apollo-server-landing-page.cdn.apollographql.com');\n directives['frame-src'].push(`'self'`);\n directives['frame-src'].push('sandbox.embed.apollographql.com');\n }\n\n // TODO: we shouldn't combine playground exceptions with documentation for all routes, we should first check the path and then return exceptions specific to that\n if (ctx.method === 'GET' && specialPaths.some((str) => ctx.path.startsWith(str))) {\n helmetConfig = mergeConfig(helmetConfig, {\n crossOriginEmbedderPolicy: false, // TODO: only use this for graphql playground\n contentSecurityPolicy: {\n directives,\n },\n });\n }\n\n /**\n * These are for vite's watch mode so it can accurately\n * connect to the HMR websocket & reconnect on failure\n * or when the server restarts.\n *\n * It only applies in development, and only on GET requests\n * that are part of the admin route.\n */\n\n if (\n ['development', 'test'].includes(process.env.NODE_ENV ?? '') &&\n ctx.method === 'GET' &&\n ctx.path.startsWith(strapi.config.get('admin.path'))\n ) {\n helmetConfig = mergeConfig(helmetConfig, {\n contentSecurityPolicy: {\n directives: {\n 'script-src': [\"'self'\", \"'unsafe-inline'\"],\n 'connect-src': [\"'self'\", 'http:', 'https:', 'ws:'],\n },\n },\n });\n }\n\n return helmet(helmetConfig)(ctx, next);\n };\n"],"names":["defaults","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","originAgentCluster","contentSecurityPolicy","useDefaults","directives","CSP_DEFAULTS","upgradeInsecureRequests","xssFilter","hsts","maxAge","includeSubDomains","frameguard","action","mergeConfig","existingConfig","newConfig","mergeWith","obj","src","Array","isArray","concat","undefined","security","config","strapi","ctx","next","helmetConfig","defaultsDeep","specialPaths","plugin","service","playground","isEnabled","gqlConfig","push","method","some","str","path","startsWith","includes","process","env","NODE_ENV","get","helmet"],"mappings":";;;;;;AAQA,MAAMA,QAAmB,GAAA;IACvBC,yBAA2B,EAAA,KAAA;IAC3BC,uBAAyB,EAAA,KAAA;IACzBC,yBAA2B,EAAA,KAAA;IAC3BC,kBAAoB,EAAA,KAAA;IACpBC,qBAAuB,EAAA;QACrBC,WAAa,EAAA,IAAA;QACbC,UAAY,EAAA;AACV,YAAA,GAAGC,wBAAY;YACfC,uBAAyB,EAAA;AAC3B;AACF,KAAA;IACAC,SAAW,EAAA,KAAA;IACXC,IAAM,EAAA;QACJC,MAAQ,EAAA,QAAA;QACRC,iBAAmB,EAAA;AACrB,KAAA;IACAC,UAAY,EAAA;QACVC,MAAQ,EAAA;AACV;AACF,CAAA;AAEA,MAAMC,WAAAA,GAAc,CAACC,cAAwBC,EAAAA,SAAAA,GAAAA;AAC3C,IAAA,OAAOC,aACL,CAACC,GAAAA,EAAKC,GAASC,GAAAA,KAAAA,CAAMC,OAAO,CAACH,GAAAA,CAAAA,IAAQE,KAAMC,CAAAA,OAAO,CAACF,GAAOD,CAAAA,GAAAA,GAAAA,CAAII,MAAM,CAACH,GAAAA,CAAAA,GAAOI,WAC5ER,cACAC,EAAAA,SAAAA,CAAAA;AAEJ,CAAA;AAEO,MAAMQ,WACX,CAACC,MAAAA,EAAQ,EAAEC,MAAM,EAAE,GACnB,CAACC,GAAKC,EAAAA,IAAAA,GAAAA;QACJ,IAAIC,YAAAA,GAAuBC,gBAAahC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GAAIc,CAAAA,IAAI,CAACC,UAAU,CAACF,GAAO,CAAA,CAAA,EAAA;AAChFX,YAAAA,YAAAA,GAAef,YAAYe,YAAc,EAAA;gBACvC9B,yBAA2B,EAAA,KAAA;gBAC3BI,qBAAuB,EAAA;AACrBE,oBAAAA;AACF;AACF,aAAA,CAAA;AACF;AAEA;;;;;;;AAOC,QAED,IACE;AAAC,YAAA,aAAA;AAAe,YAAA;SAAO,CAACsC,QAAQ,CAACC,OAAQC,CAAAA,GAAG,CAACC,QAAQ,IAAI,EACzDnB,CAAAA,IAAAA,GAAAA,CAAIW,MAAM,KAAK,SACfX,GAAIc,CAAAA,IAAI,CAACC,UAAU,CAAChB,OAAOD,MAAM,CAACsB,GAAG,CAAC,YACtC,CAAA,CAAA,EAAA;AACAlB,YAAAA,YAAAA,GAAef,YAAYe,YAAc,EAAA;gBACvC1B,qBAAuB,EAAA;oBACrBE,UAAY,EAAA;wBACV,YAAc,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA;AAAkB,yBAAA;wBAC3C,aAAe,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA,OAAA;AAAS,4BAAA,QAAA;AAAU,4BAAA;AAAM;AACrD;AACF;AACF,aAAA,CAAA;AACF;QAEA,OAAO2C,MAAAA,CAAOnB,cAAcF,GAAKC,EAAAA,IAAAA,CAAAA;;;;;"}
@@ -1,5 +1,6 @@
1
1
  import { defaultsDeep, mergeWith } from 'lodash/fp';
2
2
  import helmet from 'koa-helmet';
3
+ import { CSP_DEFAULTS } from '@strapi/utils';
3
4
 
4
5
  const defaults = {
5
6
  crossOriginEmbedderPolicy: false,
@@ -9,21 +10,7 @@ const defaults = {
9
10
  contentSecurityPolicy: {
10
11
  useDefaults: true,
11
12
  directives: {
12
- 'connect-src': [
13
- "'self'",
14
- 'https:'
15
- ],
16
- 'img-src': [
17
- "'self'",
18
- 'data:',
19
- 'blob:',
20
- 'https://market-assets.strapi.io'
21
- ],
22
- 'media-src': [
23
- "'self'",
24
- 'data:',
25
- 'blob:'
26
- ],
13
+ ...CSP_DEFAULTS,
27
14
  upgradeInsecureRequests: null
28
15
  }
29
16
  },
@@ -1 +1 @@
1
- {"version":3,"file":"security.mjs","sources":["../../src/middlewares/security.ts"],"sourcesContent":["import { defaultsDeep, mergeWith } from 'lodash/fp';\nimport helmet, { KoaHelmet } from 'koa-helmet';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = NonNullable<Parameters<KoaHelmet>[0]>;\n\nconst defaults: Config = {\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n contentSecurityPolicy: {\n useDefaults: true,\n directives: {\n 'connect-src': [\"'self'\", 'https:'],\n 'img-src': [\"'self'\", 'data:', 'blob:', 'https://market-assets.strapi.io'],\n 'media-src': [\"'self'\", 'data:', 'blob:'],\n upgradeInsecureRequests: null,\n },\n },\n xssFilter: false,\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n },\n frameguard: {\n action: 'sameorigin',\n },\n};\n\nconst mergeConfig = (existingConfig: Config, newConfig: Config) => {\n return mergeWith(\n (obj, src) => (Array.isArray(obj) && Array.isArray(src) ? obj.concat(src) : undefined),\n existingConfig,\n newConfig\n );\n};\n\nexport const security: Core.MiddlewareFactory<Config> =\n (config, { strapi }) =>\n (ctx, next) => {\n let helmetConfig: Config = defaultsDeep(defaults, config);\n\n const specialPaths = ['/documentation'];\n\n const directives: {\n 'script-src': string[];\n 'img-src': string[];\n 'manifest-src': string[];\n 'frame-src': string[];\n } = {\n 'script-src': [\"'self'\", \"'unsafe-inline'\", 'cdn.jsdelivr.net'],\n 'img-src': [\"'self'\", 'data:', 'cdn.jsdelivr.net', 'strapi.io'],\n 'manifest-src': [],\n 'frame-src': [],\n };\n\n // if apollo graphql playground is enabled, add exceptions for it\n if (strapi.plugin('graphql')?.service('utils').playground.isEnabled()) {\n const { config: gqlConfig } = strapi.plugin('graphql');\n specialPaths.push(gqlConfig('endpoint'));\n\n directives['script-src'].push(`https: 'unsafe-inline'`);\n directives['img-src'].push(`'apollo-server-landing-page.cdn.apollographql.com'`);\n directives['manifest-src'].push(`'self'`);\n directives['manifest-src'].push('apollo-server-landing-page.cdn.apollographql.com');\n directives['frame-src'].push(`'self'`);\n directives['frame-src'].push('sandbox.embed.apollographql.com');\n }\n\n // TODO: we shouldn't combine playground exceptions with documentation for all routes, we should first check the path and then return exceptions specific to that\n if (ctx.method === 'GET' && specialPaths.some((str) => ctx.path.startsWith(str))) {\n helmetConfig = mergeConfig(helmetConfig, {\n crossOriginEmbedderPolicy: false, // TODO: only use this for graphql playground\n contentSecurityPolicy: {\n directives,\n },\n });\n }\n\n /**\n * These are for vite's watch mode so it can accurately\n * connect to the HMR websocket & reconnect on failure\n * or when the server restarts.\n *\n * It only applies in development, and only on GET requests\n * that are part of the admin route.\n */\n\n if (\n ['development', 'test'].includes(process.env.NODE_ENV ?? '') &&\n ctx.method === 'GET' &&\n ctx.path.startsWith(strapi.config.get('admin.path'))\n ) {\n helmetConfig = mergeConfig(helmetConfig, {\n contentSecurityPolicy: {\n directives: {\n 'script-src': [\"'self'\", \"'unsafe-inline'\"],\n 'connect-src': [\"'self'\", 'http:', 'https:', 'ws:'],\n },\n },\n });\n }\n\n return helmet(helmetConfig)(ctx, next);\n };\n"],"names":["defaults","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","originAgentCluster","contentSecurityPolicy","useDefaults","directives","upgradeInsecureRequests","xssFilter","hsts","maxAge","includeSubDomains","frameguard","action","mergeConfig","existingConfig","newConfig","mergeWith","obj","src","Array","isArray","concat","undefined","security","config","strapi","ctx","next","helmetConfig","defaultsDeep","specialPaths","plugin","service","playground","isEnabled","gqlConfig","push","method","some","str","path","startsWith","includes","process","env","NODE_ENV","get","helmet"],"mappings":";;;AAOA,MAAMA,QAAmB,GAAA;IACvBC,yBAA2B,EAAA,KAAA;IAC3BC,uBAAyB,EAAA,KAAA;IACzBC,yBAA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OC,QAED,IACE;AAAC,YAAA,aAAA;AAAe,YAAA;SAAO,CAACqC,QAAQ,CAACC,OAAQC,CAAAA,GAAG,CAACC,QAAQ,IAAI,EACzDnB,CAAAA,IAAAA,GAAAA,CAAIW,MAAM,KAAK,SACfX,GAAIc,CAAAA,IAAI,CAACC,UAAU,CAAChB,OAAOD,MAAM,CAACsB,GAAG,CAAC,YACtC,CAAA,CAAA,EAAA;AACAlB,YAAAA,YAAAA,GAAef,YAAYe,YAAc,EAAA;gBACvCzB,qBAAuB,EAAA;oBACrBE,UAAY,EAAA;wBACV,YAAc,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA;AAAkB,yBAAA;wBAC3C,aAAe,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA,OAAA;AAAS,4BAAA,QAAA;AAAU,4BAAA;AAAM;AACrD;AACF;AACF,aAAA,CAAA;AACF;QAEA,OAAO0C,MAAAA,CAAOnB,cAAcF,GAAKC,EAAAA,IAAAA,CAAAA;;;;;"}
1
+ {"version":3,"file":"security.mjs","sources":["../../src/middlewares/security.ts"],"sourcesContent":["import { defaultsDeep, mergeWith } from 'lodash/fp';\nimport helmet, { KoaHelmet } from 'koa-helmet';\nimport { CSP_DEFAULTS } from '@strapi/utils';\n\nimport type { Core } from '@strapi/types';\n\nexport type Config = NonNullable<Parameters<KoaHelmet>[0]>;\n\nconst defaults: Config = {\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n contentSecurityPolicy: {\n useDefaults: true,\n directives: {\n ...CSP_DEFAULTS,\n upgradeInsecureRequests: null,\n },\n },\n xssFilter: false,\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n },\n frameguard: {\n action: 'sameorigin',\n },\n};\n\nconst mergeConfig = (existingConfig: Config, newConfig: Config) => {\n return mergeWith(\n (obj, src) => (Array.isArray(obj) && Array.isArray(src) ? obj.concat(src) : undefined),\n existingConfig,\n newConfig\n );\n};\n\nexport const security: Core.MiddlewareFactory<Config> =\n (config, { strapi }) =>\n (ctx, next) => {\n let helmetConfig: Config = defaultsDeep(defaults, config);\n const specialPaths = ['/documentation'];\n\n const directives: {\n 'script-src': string[];\n 'img-src': string[];\n 'manifest-src': string[];\n 'frame-src': string[];\n } = {\n 'script-src': [\"'self'\", \"'unsafe-inline'\", 'cdn.jsdelivr.net'],\n 'img-src': [\"'self'\", 'data:', 'cdn.jsdelivr.net', 'strapi.io'],\n 'manifest-src': [],\n 'frame-src': [],\n };\n\n // if apollo graphql playground is enabled, add exceptions for it\n if (strapi.plugin('graphql')?.service('utils').playground.isEnabled()) {\n const { config: gqlConfig } = strapi.plugin('graphql');\n specialPaths.push(gqlConfig('endpoint'));\n\n directives['script-src'].push(`https: 'unsafe-inline'`);\n directives['img-src'].push(`'apollo-server-landing-page.cdn.apollographql.com'`);\n directives['manifest-src'].push(`'self'`);\n directives['manifest-src'].push('apollo-server-landing-page.cdn.apollographql.com');\n directives['frame-src'].push(`'self'`);\n directives['frame-src'].push('sandbox.embed.apollographql.com');\n }\n\n // TODO: we shouldn't combine playground exceptions with documentation for all routes, we should first check the path and then return exceptions specific to that\n if (ctx.method === 'GET' && specialPaths.some((str) => ctx.path.startsWith(str))) {\n helmetConfig = mergeConfig(helmetConfig, {\n crossOriginEmbedderPolicy: false, // TODO: only use this for graphql playground\n contentSecurityPolicy: {\n directives,\n },\n });\n }\n\n /**\n * These are for vite's watch mode so it can accurately\n * connect to the HMR websocket & reconnect on failure\n * or when the server restarts.\n *\n * It only applies in development, and only on GET requests\n * that are part of the admin route.\n */\n\n if (\n ['development', 'test'].includes(process.env.NODE_ENV ?? '') &&\n ctx.method === 'GET' &&\n ctx.path.startsWith(strapi.config.get('admin.path'))\n ) {\n helmetConfig = mergeConfig(helmetConfig, {\n contentSecurityPolicy: {\n directives: {\n 'script-src': [\"'self'\", \"'unsafe-inline'\"],\n 'connect-src': [\"'self'\", 'http:', 'https:', 'ws:'],\n },\n },\n });\n }\n\n return helmet(helmetConfig)(ctx, next);\n };\n"],"names":["defaults","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","originAgentCluster","contentSecurityPolicy","useDefaults","directives","CSP_DEFAULTS","upgradeInsecureRequests","xssFilter","hsts","maxAge","includeSubDomains","frameguard","action","mergeConfig","existingConfig","newConfig","mergeWith","obj","src","Array","isArray","concat","undefined","security","config","strapi","ctx","next","helmetConfig","defaultsDeep","specialPaths","plugin","service","playground","isEnabled","gqlConfig","push","method","some","str","path","startsWith","includes","process","env","NODE_ENV","get","helmet"],"mappings":";;;;AAQA,MAAMA,QAAmB,GAAA;IACvBC,yBAA2B,EAAA,KAAA;IAC3BC,uBAAyB,EAAA,KAAA;IACzBC,yBAA2B,EAAA,KAAA;IAC3BC,kBAAoB,EAAA,KAAA;IACpBC,qBAAuB,EAAA;QACrBC,WAAa,EAAA,IAAA;QACbC,UAAY,EAAA;AACV,YAAA,GAAGC,YAAY;YACfC,uBAAyB,EAAA;AAC3B;AACF,KAAA;IACAC,SAAW,EAAA,KAAA;IACXC,IAAM,EAAA;QACJC,MAAQ,EAAA,QAAA;QACRC,iBAAmB,EAAA;AACrB,KAAA;IACAC,UAAY,EAAA;QACVC,MAAQ,EAAA;AACV;AACF,CAAA;AAEA,MAAMC,WAAAA,GAAc,CAACC,cAAwBC,EAAAA,SAAAA,GAAAA;AAC3C,IAAA,OAAOC,UACL,CAACC,GAAAA,EAAKC,GAASC,GAAAA,KAAAA,CAAMC,OAAO,CAACH,GAAAA,CAAAA,IAAQE,KAAMC,CAAAA,OAAO,CAACF,GAAOD,CAAAA,GAAAA,GAAAA,CAAII,MAAM,CAACH,GAAAA,CAAAA,GAAOI,WAC5ER,cACAC,EAAAA,SAAAA,CAAAA;AAEJ,CAAA;AAEO,MAAMQ,WACX,CAACC,MAAAA,EAAQ,EAAEC,MAAM,EAAE,GACnB,CAACC,GAAKC,EAAAA,IAAAA,GAAAA;QACJ,IAAIC,YAAAA,GAAu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A,GAAQb,GAAIc,CAAAA,IAAI,CAACC,UAAU,CAACF,GAAO,CAAA,CAAA,EAAA;AAChFX,YAAAA,YAAAA,GAAef,YAAYe,YAAc,EAAA;gBACvC9B,yBAA2B,EAAA,KAAA;gBAC3BI,qBAAuB,EAAA;AACrBE,oBAAAA;AACF;AACF,aAAA,CAAA;AACF;AAEA;;;;;;;AAOC,QAED,IACE;AAAC,YAAA,aAAA;AAAe,YAAA;SAAO,CAACsC,QAAQ,CAACC,OAAQC,CAAAA,GAAG,CAACC,QAAQ,IAAI,EACzDnB,CAAAA,IAAAA,GAAAA,CAAIW,MAAM,KAAK,SACfX,GAAIc,CAAAA,IAAI,CAACC,UAAU,CAAChB,OAAOD,MAAM,CAACsB,GAAG,CAAC,YACtC,CAAA,CAAA,EAAA;AACAlB,YAAAA,YAAAA,GAAef,YAAYe,YAAc,EAAA;gBACvC1B,qBAAuB,EAAA;oBACrBE,UAAY,EAAA;wBACV,YAAc,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA;AAAkB,yBAAA;wBAC3C,aAAe,EAAA;AAAC,4BAAA,QAAA;AAAU,4BAAA,OAAA;AAAS,4BAAA,QAAA;AAAU,4BAAA;AAAM;AACrD;AACF;AACF,aAAA,CAAA;AACF;QAEA,OAAO2C,MAAAA,CAAOnB,cAAcF,GAAKC,EAAAA,IAAAA,CAAAA;;;;;"}
@@ -100,7 +100,7 @@ var index = require('../../services/document-service/index.js');
100
100
  * And then discard the drafts to copy the relations.
101
101
  */ const migrateUp = async (trx, db)=>{
102
102
  const dpModels = [];
103
- for (const meta of db.metadata.values()){
103
+ for (const meta of Array.from(db.metadata.values())){
104
104
  const hasDP = await hasDraftAndPublish(trx, meta);
105
105
  if (hasDP) {
106
106
  dpModels.push(meta);
@@ -1 +1 @@
1
- {"version":3,"file":"5.0.0-discard-drafts.js","sources":["../../../src/migrations/database/5.0.0-discard-drafts.ts"],"sourcesContent":["/**\n * This migration is responsible for creating the draft counterpart for all the entries that were in a published state.\n *\n * In v4, entries could either be in a draft or published state, but not both at the same time.\n * In v5, we introduced the concept of document, and an entry can be in a draft or published state.\n *\n * This means the migration needs to create the draft counterpart if an entry was published.\n *\n * This migration performs the following steps:\n * 1. Creates draft entries for all published entries, without it's components, dynamic zones or relations.\n * 2. Using the document service, discard those same drafts to copy its relations.\n */\n\n/* eslint-disable no-continue */\nimport type { UID } from '@strapi/types';\nimport type { Database, Migration } from '@strapi/database';\nimport { async, contentTypes } from '@strapi/utils';\nimport { createDocumentService } from '../../services/document-service';\n\ntype DocumentVersion = { documentId: string; locale: string };\ntype Knex = Parameters<Migration['up']>[0];\n\n/**\n * Check if the model has draft and publish enabled.\n */\nconst hasDraftAndPublish = async (trx: Knex, meta: any) => {\n const hasTable = await trx.schema.hasTable(meta.tableName);\n\n if (!hasTable) {\n return false;\n }\n\n const uid = meta.uid as UID.ContentType;\n const model = strapi.getModel(uid);\n const hasDP = contentTypes.hasDraftAndPublish(model);\n if (!hasDP) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Copy all the published entries to draft entries, without it's components, dynamic zones or relations.\n * This ensures all necessary draft's exist before copying it's relations.\n */\nasync function copyPublishedEntriesToDraft({\n db,\n trx,\n uid,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n}) {\n // Extract all scalar attributes to use in the insert query\n const meta = db.metadata.get(uid);\n\n // Get scalar attributes that will be copied over the new draft\n const scalarAttributes = Object.values(meta.attributes).reduce((acc, attribute: any) => {\n if (['id'].includes(attribute.columnName)) {\n return acc;\n }\n\n if (contentTypes.isScalarAttribute(attribute)) {\n acc.push(attribute.columnName);\n }\n\n return acc;\n }, [] as string[]);\n\n /**\n * Query to copy the published entries into draft entries.\n *\n * INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n * SELECT columnName1, columnName2, columnName3, ...\n * FROM tableName\n */\n await trx\n // INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n .into(\n trx.raw(`?? (${scalarAttributes.map(() => `??`).join(', ')})`, [\n meta.tableName,\n ...scalarAttributes,\n ])\n )\n .insert((subQb: typeof trx) => {\n // SELECT columnName1, columnName2, columnName3, ...\n subQb\n .select(\n ...scalarAttributes.map((att: string) => {\n // Override 'publishedAt' and 'updatedAt' attributes\n if (att === 'published_at') {\n return trx.raw('NULL as ??', 'published_at');\n }\n\n return att;\n })\n )\n .from(meta.tableName)\n // Only select entries that were published\n .whereNotNull('published_at');\n });\n}\n\n/**\n * Load a batch of versions to discard.\n *\n * Versions with only a draft version will be ignored.\n * Only versions with a published version (which always have a draft version) will be discarded.\n */\nexport async function* getBatchToDiscard({\n db,\n trx,\n uid,\n defaultBatchSize = 1000,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n defaultBatchSize?: number;\n}) {\n const client = db.config.connection.client;\n const isSQLite =\n typeof client === 'string' && ['sqlite', 'sqlite3', 'better-sqlite3'].includes(client);\n\n // The SQLite documentation states that the maximum number of terms in a\n // compound SELECT statement is 500 by default.\n // See: https://www.sqlite.org/limits.html\n // To ensure a successful migration, we limit the batch size to 500 for SQLite.\n const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;\n let offset = 0;\n let hasMore = true;\n\n while (hasMore) {\n // Look for the published entries to discard\n const batch: DocumentVersion[] = await db\n .queryBuilder(uid)\n .select(['id', 'documentId', 'locale'])\n .where({ publishedAt: { $ne: null } })\n .limit(batchSize)\n .offset(offset)\n .orderBy('id')\n .transacting(trx)\n .execute();\n\n if (batch.length < batchSize) {\n hasMore = false;\n }\n\n offset += batchSize;\n yield batch;\n }\n}\n\n/**\n * 2 pass migration to create the draft entries for all the published entries.\n * And then discard the drafts to copy the relations.\n */\nconst migrateUp = async (trx: Knex, db: Database) => {\n const dpModels = [];\n for (const meta of db.metadata.values()) {\n const hasDP = await hasDraftAndPublish(trx, meta);\n if (hasDP) {\n dpModels.push(meta);\n }\n }\n\n /**\n * Create plain draft entries for all the entries that were published.\n */\n for (const model of dpModels) {\n await copyPublishedEntriesToDraft({ db, trx, uid: model.uid });\n }\n\n /**\n * Discard the drafts will copy the relations from the published entries to the newly created drafts.\n *\n * Load a batch of entries (batched to prevent loading millions of rows at once ),\n * and discard them using the document service.\n *\n * NOTE: This is using a custom document service without any validations,\n * to prevent the migration from failing if users already had invalid data in V4.\n * E.g. @see https://github.com/strapi/strapi/issues/21583\n */\n const documentService = createDocumentService(strapi, {\n async validateEntityCreation(_, data) {\n return data;\n },\n async validateEntityUpdate(_, data) {\n // Data can be partially empty on partial updates\n // This migration doesn't trigger any update (or partial update),\n // so it's safe to return the data as is.\n return data as any;\n },\n });\n\n for (const model of dpModels) {\n const discardDraft = async (entry: DocumentVersion) =>\n documentService(model.uid as UID.ContentType).discardDraft({\n documentId: entry.documentId,\n locale: entry.locale,\n });\n\n for await (const batch of getBatchToDiscard({ db, trx, uid: model.uid })) {\n // NOTE: concurrency had to be disabled to prevent a race condition with self-references\n // TODO: improve performance in a safe way\n await async.map(batch, discardDraft, { concurrency: 1 });\n }\n }\n};\n\nexport const discardDocumentDrafts: Migration = {\n name: 'core::5.0.0-discard-drafts',\n async up(trx, db) {\n await migrateUp(trx, db);\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["hasDraftAndPublish","trx","meta","hasTable","schema","tableName","uid","model","strapi","getModel","hasDP","contentTypes","copyPublishedEntriesToDraft","db","metadata","get","scalarAttributes","Object","values","attributes","reduce","acc","attribute","includes","columnName","isScalarAttribute","push","into","raw","map","join","insert","subQb","select","att","from","whereNotNull","getBatchToDiscard","defaultBatchSize","client","config","connection","isSQLite","batchSize","Math","min","offset","hasMore","batch","queryBuilder","where","publishedAt","$ne","limit","orderBy","transacting","execute","length","migrateUp","dpModels","documentService","createDocumentService","validateEntityCreation","_","data","validateEntityUpdate","discardDraft","entry","documentId","locale","async","concurrency","discardDocumentDrafts","name","up","down","Error"],"mappings":";;;;;AAsBA;;IAGA,MAAMA,kBAAqB,GAAA,OAAOC,GAAWC,EAAAA,IAAAA,GAAAA;IAC3C,MAAMC,QAAAA,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QAAU,CAAA;QAC5B,MAAMO,YAAAA,GAAe,OAAOC,KAC1BP,GAAAA,eAAAA,CAAgBrD,MAAMD,GAAG,CAAA,CAAqB4D,YAAY,CAAC;AACzDE,gBAAAA,UAAAA,EAAYD,MAAMC,UAAU;AAC5BC,gBAAAA,MAAAA,EAAQF,MAAME;AAChB,aAAA,CAAA;QAEF,WAAW,MAAMrB,SAASX,iBAAkB,CAAA;AAAExB,YAAAA,EAAAA;AAAIZ,YAAAA,GAAAA;AAAKK,YAAAA,GAAAA,EAAKC,MAAMD;SAAQ,CAAA,CAAA;;;AAGxE,YAAA,MAAMgE,iBAAMzC,CAAAA,GAAG,CAACmB,KAAAA,EAAOkB,YAAc,EAAA;gBAAEK,WAAa,EAAA;AAAE,aAAA,CAAA;AACxD;AACF;AACF,CAAA;MAEaC,qBAAmC,GAAA;IAC9CC,IAAM,EAAA,4BAAA;IACN,MAAMC,EAAAA,CAAAA,CAAGzE,GAAG,EAAEY,EAAE,EAAA;AACd,QAAA,MAAM6C,UAAUzD,GAAKY,EAAAA,EAAAA,CAAAA;AACvB,KAAA;IACA,MAAM8D,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAM,CAAA,iBAAA,CAAA;AAClB;AACF;;;;;"}
1
+ {"version":3,"file":"5.0.0-discard-drafts.js","sources":["../../../src/migrations/database/5.0.0-discard-drafts.ts"],"sourcesContent":["/**\n * This migration is responsible for creating the draft counterpart for all the entries that were in a published state.\n *\n * In v4, entries could either be in a draft or published state, but not both at the same time.\n * In v5, we introduced the concept of document, and an entry can be in a draft or published state.\n *\n * This means the migration needs to create the draft counterpart if an entry was published.\n *\n * This migration performs the following steps:\n * 1. Creates draft entries for all published entries, without it's components, dynamic zones or relations.\n * 2. Using the document service, discard those same drafts to copy its relations.\n */\n\n/* eslint-disable no-continue */\nimport type { UID } from '@strapi/types';\nimport type { Database, Migration } from '@strapi/database';\nimport { async, contentTypes } from '@strapi/utils';\nimport { createDocumentService } from '../../services/document-service';\n\ntype DocumentVersion = { documentId: string; locale: string };\ntype Knex = Parameters<Migration['up']>[0];\n\n/**\n * Check if the model has draft and publish enabled.\n */\nconst hasDraftAndPublish = async (trx: Knex, meta: any) => {\n const hasTable = await trx.schema.hasTable(meta.tableName);\n\n if (!hasTable) {\n return false;\n }\n\n const uid = meta.uid as UID.ContentType;\n const model = strapi.getModel(uid);\n const hasDP = contentTypes.hasDraftAndPublish(model);\n if (!hasDP) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Copy all the published entries to draft entries, without it's components, dynamic zones or relations.\n * This ensures all necessary draft's exist before copying it's relations.\n */\nasync function copyPublishedEntriesToDraft({\n db,\n trx,\n uid,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n}) {\n // Extract all scalar attributes to use in the insert query\n const meta = db.metadata.get(uid);\n\n // Get scalar attributes that will be copied over the new draft\n const scalarAttributes = Object.values(meta.attributes).reduce((acc, attribute: any) => {\n if (['id'].includes(attribute.columnName)) {\n return acc;\n }\n\n if (contentTypes.isScalarAttribute(attribute)) {\n acc.push(attribute.columnName);\n }\n\n return acc;\n }, [] as string[]);\n\n /**\n * Query to copy the published entries into draft entries.\n *\n * INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n * SELECT columnName1, columnName2, columnName3, ...\n * FROM tableName\n */\n await trx\n // INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n .into(\n trx.raw(`?? (${scalarAttributes.map(() => `??`).join(', ')})`, [\n meta.tableName,\n ...scalarAttributes,\n ])\n )\n .insert((subQb: typeof trx) => {\n // SELECT columnName1, columnName2, columnName3, ...\n subQb\n .select(\n ...scalarAttributes.map((att: string) => {\n // Override 'publishedAt' and 'updatedAt' attributes\n if (att === 'published_at') {\n return trx.raw('NULL as ??', 'published_at');\n }\n\n return att;\n })\n )\n .from(meta.tableName)\n // Only select entries that were published\n .whereNotNull('published_at');\n });\n}\n\n/**\n * Load a batch of versions to discard.\n *\n * Versions with only a draft version will be ignored.\n * Only versions with a published version (which always have a draft version) will be discarded.\n */\nexport async function* getBatchToDiscard({\n db,\n trx,\n uid,\n defaultBatchSize = 1000,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n defaultBatchSize?: number;\n}) {\n const client = db.config.connection.client;\n const isSQLite =\n typeof client === 'string' && ['sqlite', 'sqlite3', 'better-sqlite3'].includes(client);\n\n // The SQLite documentation states that the maximum number of terms in a\n // compound SELECT statement is 500 by default.\n // See: https://www.sqlite.org/limits.html\n // To ensure a successful migration, we limit the batch size to 500 for SQLite.\n const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;\n let offset = 0;\n let hasMore = true;\n\n while (hasMore) {\n // Look for the published entries to discard\n const batch: DocumentVersion[] = await db\n .queryBuilder(uid)\n .select(['id', 'documentId', 'locale'])\n .where({ publishedAt: { $ne: null } })\n .limit(batchSize)\n .offset(offset)\n .orderBy('id')\n .transacting(trx)\n .execute();\n\n if (batch.length < batchSize) {\n hasMore = false;\n }\n\n offset += batchSize;\n yield batch;\n }\n}\n\n/**\n * 2 pass migration to create the draft entries for all the published entries.\n * And then discard the drafts to copy the relations.\n */\nconst migrateUp = async (trx: Knex, db: Database) => {\n const dpModels = [];\n for (const meta of Array.from(db.metadata.values())) {\n const hasDP = await hasDraftAndPublish(trx, meta);\n if (hasDP) {\n dpModels.push(meta);\n }\n }\n\n /**\n * Create plain draft entries for all the entries that were published.\n */\n for (const model of dpModels) {\n await copyPublishedEntriesToDraft({ db, trx, uid: model.uid });\n }\n\n /**\n * Discard the drafts will copy the relations from the published entries to the newly created drafts.\n *\n * Load a batch of entries (batched to prevent loading millions of rows at once ),\n * and discard them using the document service.\n *\n * NOTE: This is using a custom document service without any validations,\n * to prevent the migration from failing if users already had invalid data in V4.\n * E.g. @see https://github.com/strapi/strapi/issues/21583\n */\n const documentService = createDocumentService(strapi, {\n async validateEntityCreation(_, data) {\n return data;\n },\n async validateEntityUpdate(_, data) {\n // Data can be partially empty on partial updates\n // This migration doesn't trigger any update (or partial update),\n // so it's safe to return the data as is.\n return data as any;\n },\n });\n\n for (const model of dpModels) {\n const discardDraft = async (entry: DocumentVersion) =>\n documentService(model.uid as UID.ContentType).discardDraft({\n documentId: entry.documentId,\n locale: entry.locale,\n });\n\n for await (const batch of getBatchToDiscard({ db, trx, uid: model.uid })) {\n // NOTE: concurrency had to be disabled to prevent a race condition with self-references\n // TODO: improve performance in a safe way\n await async.map(batch, discardDraft, { concurrency: 1 });\n }\n }\n};\n\nexport const discardDocumentDrafts: Migration = {\n name: 'core::5.0.0-discard-drafts',\n async up(trx, db) {\n await migrateUp(trx, db);\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["hasDraftAndPublish","trx","meta","hasTable","schema","tableName","uid","model","strapi","getModel","hasDP","contentTypes","copyPublishedEntriesToDraft","db","metadata","get","scalarAttributes","Object","values","attributes","reduce","acc","attribute","includes","columnName","isScalarAttribute","push","into","raw","map","join","insert","subQb","select","att","from","whereNotNull","getBatchToDiscard","defaultBatchSize","client","config","connection","isSQLite","batchSize","Math","min","offset","hasMore","batch","queryBuilder","where","publishedAt","$ne","limit","orderBy","transacting","execute","length","migrateUp","dpModels","Array","documentService","createDocumentService","validateEntityCreation","_","data","validateEntityUpdate","discardDraft","entry","documentId","locale","async","concurrency","discardDocumentDrafts","name","up","down","Error"],"mappings":";;;;;AAsBA;;IAGA,MAAMA,kBAAqB,GAAA,OAAOC,GAAWC,EAAAA,IAAAA,GAAAA;IAC3C,MAAMC,QAAAA,GAAW,MAAMF,GAAIG,CAAAA,MAAM,CAACD,QAAQ,CAACD,KAAKG,SAAS,CAAA;AAEzD,IAAA,IAAI,CAACF,QAAU,EAAA;QACb,OAAO,KAAA;AACT;IAEA,MAAMG,GAAAA,GAAMJ,KAAKI,GAAG;IACpB,MAAMC,KAAAA,GAAQC,MAAOC,CAAAA,QAAQ,CAACH,GAAAA,CAAAA;IAC9B,MAAMI,KAAAA,GAAQC,wBAAaX,CAAAA,kBAAkB,CAACO,KAAAA,CA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Z,YAAAA,GAAAA;AAAKK,YAAAA,GAAAA,EAAKC,MAAMD;SAAQ,CAAA,CAAA;;;AAGxE,YAAA,MAAMiE,iBAAM1C,CAAAA,GAAG,CAACmB,KAAAA,EAAOmB,YAAc,EAAA;gBAAEK,WAAa,EAAA;AAAE,aAAA,CAAA;AACxD;AACF;AACF,CAAA;MAEaC,qBAAmC,GAAA;IAC9CC,IAAM,EAAA,4BAAA;IACN,MAAMC,EAAAA,CAAAA,CAAG1E,GAAG,EAAEY,EAAE,EAAA;AACd,QAAA,MAAM6C,UAAUzD,GAAKY,EAAAA,EAAAA,CAAAA;AACvB,KAAA;IACA,MAAM+D,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAM,CAAA,iBAAA,CAAA;AAClB;AACF;;;;;"}
@@ -98,7 +98,7 @@ import { createDocumentService } from '../../services/document-service/index.mjs
98
98
  * And then discard the drafts to copy the relations.
99
99
  */ const migrateUp = async (trx, db)=>{
100
100
  const dpModels = [];
101
- for (const meta of db.metadata.values()){
101
+ for (const meta of Array.from(db.metadata.values())){
102
102
  const hasDP = await hasDraftAndPublish(trx, meta);
103
103
  if (hasDP) {
104
104
  dpModels.push(meta);
@@ -1 +1 @@
1
- {"version":3,"file":"5.0.0-discard-drafts.mjs","sources":["../../../src/migrations/database/5.0.0-discard-drafts.ts"],"sourcesContent":["/**\n * This migration is responsible for creating the draft counterpart for all the entries that were in a published state.\n *\n * In v4, entries could either be in a draft or published state, but not both at the same time.\n * In v5, we introduced the concept of document, and an entry can be in a draft or published state.\n *\n * This means the migration needs to create the draft counterpart if an entry was published.\n *\n * This migration performs the following steps:\n * 1. Creates draft entries for all published entries, without it's components, dynamic zones or relations.\n * 2. Using the document service, discard those same drafts to copy its relations.\n */\n\n/* eslint-disable no-continue */\nimport type { UID } from '@strapi/types';\nimport type { Database, Migration } from '@strapi/database';\nimport { async, contentTypes } from '@strapi/utils';\nimport { createDocumentService } from '../../services/document-service';\n\ntype DocumentVersion = { documentId: string; locale: string };\ntype Knex = Parameters<Migration['up']>[0];\n\n/**\n * Check if the model has draft and publish enabled.\n */\nconst hasDraftAndPublish = async (trx: Knex, meta: any) => {\n const hasTable = await trx.schema.hasTable(meta.tableName);\n\n if (!hasTable) {\n return false;\n }\n\n const uid = meta.uid as UID.ContentType;\n const model = strapi.getModel(uid);\n const hasDP = contentTypes.hasDraftAndPublish(model);\n if (!hasDP) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Copy all the published entries to draft entries, without it's components, dynamic zones or relations.\n * This ensures all necessary draft's exist before copying it's relations.\n */\nasync function copyPublishedEntriesToDraft({\n db,\n trx,\n uid,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n}) {\n // Extract all scalar attributes to use in the insert query\n const meta = db.metadata.get(uid);\n\n // Get scalar attributes that will be copied over the new draft\n const scalarAttributes = Object.values(meta.attributes).reduce((acc, attribute: any) => {\n if (['id'].includes(attribute.columnName)) {\n return acc;\n }\n\n if (contentTypes.isScalarAttribute(attribute)) {\n acc.push(attribute.columnName);\n }\n\n return acc;\n }, [] as string[]);\n\n /**\n * Query to copy the published entries into draft entries.\n *\n * INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n * SELECT columnName1, columnName2, columnName3, ...\n * FROM tableName\n */\n await trx\n // INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n .into(\n trx.raw(`?? (${scalarAttributes.map(() => `??`).join(', ')})`, [\n meta.tableName,\n ...scalarAttributes,\n ])\n )\n .insert((subQb: typeof trx) => {\n // SELECT columnName1, columnName2, columnName3, ...\n subQb\n .select(\n ...scalarAttributes.map((att: string) => {\n // Override 'publishedAt' and 'updatedAt' attributes\n if (att === 'published_at') {\n return trx.raw('NULL as ??', 'published_at');\n }\n\n return att;\n })\n )\n .from(meta.tableName)\n // Only select entries that were published\n .whereNotNull('published_at');\n });\n}\n\n/**\n * Load a batch of versions to discard.\n *\n * Versions with only a draft version will be ignored.\n * Only versions with a published version (which always have a draft version) will be discarded.\n */\nexport async function* getBatchToDiscard({\n db,\n trx,\n uid,\n defaultBatchSize = 1000,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n defaultBatchSize?: number;\n}) {\n const client = db.config.connection.client;\n const isSQLite =\n typeof client === 'string' && ['sqlite', 'sqlite3', 'better-sqlite3'].includes(client);\n\n // The SQLite documentation states that the maximum number of terms in a\n // compound SELECT statement is 500 by default.\n // See: https://www.sqlite.org/limits.html\n // To ensure a successful migration, we limit the batch size to 500 for SQLite.\n const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;\n let offset = 0;\n let hasMore = true;\n\n while (hasMore) {\n // Look for the published entries to discard\n const batch: DocumentVersion[] = await db\n .queryBuilder(uid)\n .select(['id', 'documentId', 'locale'])\n .where({ publishedAt: { $ne: null } })\n .limit(batchSize)\n .offset(offset)\n .orderBy('id')\n .transacting(trx)\n .execute();\n\n if (batch.length < batchSize) {\n hasMore = false;\n }\n\n offset += batchSize;\n yield batch;\n }\n}\n\n/**\n * 2 pass migration to create the draft entries for all the published entries.\n * And then discard the drafts to copy the relations.\n */\nconst migrateUp = async (trx: Knex, db: Database) => {\n const dpModels = [];\n for (const meta of db.metadata.values()) {\n const hasDP = await hasDraftAndPublish(trx, meta);\n if (hasDP) {\n dpModels.push(meta);\n }\n }\n\n /**\n * Create plain draft entries for all the entries that were published.\n */\n for (const model of dpModels) {\n await copyPublishedEntriesToDraft({ db, trx, uid: model.uid });\n }\n\n /**\n * Discard the drafts will copy the relations from the published entries to the newly created drafts.\n *\n * Load a batch of entries (batched to prevent loading millions of rows at once ),\n * and discard them using the document service.\n *\n * NOTE: This is using a custom document service without any validations,\n * to prevent the migration from failing if users already had invalid data in V4.\n * E.g. @see https://github.com/strapi/strapi/issues/21583\n */\n const documentService = createDocumentService(strapi, {\n async validateEntityCreation(_, data) {\n return data;\n },\n async validateEntityUpdate(_, data) {\n // Data can be partially empty on partial updates\n // This migration doesn't trigger any update (or partial update),\n // so it's safe to return the data as is.\n return data as any;\n },\n });\n\n for (const model of dpModels) {\n const discardDraft = async (entry: DocumentVersion) =>\n documentService(model.uid as UID.ContentType).discardDraft({\n documentId: entry.documentId,\n locale: entry.locale,\n });\n\n for await (const batch of getBatchToDiscard({ db, trx, uid: model.uid })) {\n // NOTE: concurrency had to be disabled to prevent a race condition with self-references\n // TODO: improve performance in a safe way\n await async.map(batch, discardDraft, { concurrency: 1 });\n }\n }\n};\n\nexport const discardDocumentDrafts: Migration = {\n name: 'core::5.0.0-discard-drafts',\n async up(trx, db) {\n await migrateUp(trx, db);\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["hasDraftAndPublish","trx","meta","hasTable","schema","tableName","uid","model","strapi","getModel","hasDP","contentTypes","copyPublishedEntriesToDraft","db","metadata","get","scalarAttributes","Object","values","attributes","reduce","acc","attribute","includes","columnName","isScalarAttribute","push","into","raw","map","join","insert","subQb","select","att","from","whereNotNull","getBatchToDiscard","defaultBatchSize","client","config","connection","isSQLite","batchSize","Math","min","offset","hasMore","batch","queryBuilder","where","publishedAt","$ne","limit","orderBy","transacting","execute","length","migrateUp","dpModels","documentService","createDocumentService","validateEntityCreation","_","data","validateEntityUpdate","discardDraft","entry","documentId","locale","async","concurrency","discardDocumentDrafts","name","up","down","Error"],"mappings":";;;AAsBA;;IAGA,MAAMA,kBAAqB,GAAA,OAAOC,GAAWC,EAAAA,IAAAA,GAAAA;IAC3C,MAAMC,QAAAA,GAAW,MAAMF,GAAIG,CAAAA,MAAM,CAACD,QAAQ,CAACD,KAAKG,SAAS,CAAA;AAEzD,IAAA,IAAI,CAACF,QAAU,EAAA;QACb,OAAO,KAAA;AACT;IAEA,MAAMG,GAAAA,GAAMJ,KAAKI,GAAG;IACpB,MAAMC,KAAAA,GAAQC,MAAOC,CAAAA,QAAQ,CAACH,GAAAA,CAAAA;IAC9B,MAAMI,KAAAA,GAAQC,YAAaX,CAAAA,kBAAkB,CAACO,KAAAA,CAAAA;AAC9C,IAAA,IAAI,CAACG,KAAO,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AAA,CAAA;;;AAGxE,YAAA,MAAMgE,KAAMzC,CAAAA,GAAG,CAACmB,KAAAA,EAAOkB,YAAc,EAAA;gBAAEK,WAAa,EAAA;AAAE,aAAA,CAAA;AACxD;AACF;AACF,CAAA;MAEaC,qBAAmC,GAAA;IAC9CC,IAAM,EAAA,4BAAA;IACN,MAAMC,EAAAA,CAAAA,CAAGzE,GAAG,EAAEY,EAAE,EAAA;AACd,QAAA,MAAM6C,UAAUzD,GAAKY,EAAAA,EAAAA,CAAAA;AACvB,KAAA;IACA,MAAM8D,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAM,CAAA,iBAAA,CAAA;AAClB;AACF;;;;"}
1
+ {"version":3,"file":"5.0.0-discard-drafts.mjs","sources":["../../../src/migrations/database/5.0.0-discard-drafts.ts"],"sourcesContent":["/**\n * This migration is responsible for creating the draft counterpart for all the entries that were in a published state.\n *\n * In v4, entries could either be in a draft or published state, but not both at the same time.\n * In v5, we introduced the concept of document, and an entry can be in a draft or published state.\n *\n * This means the migration needs to create the draft counterpart if an entry was published.\n *\n * This migration performs the following steps:\n * 1. Creates draft entries for all published entries, without it's components, dynamic zones or relations.\n * 2. Using the document service, discard those same drafts to copy its relations.\n */\n\n/* eslint-disable no-continue */\nimport type { UID } from '@strapi/types';\nimport type { Database, Migration } from '@strapi/database';\nimport { async, contentTypes } from '@strapi/utils';\nimport { createDocumentService } from '../../services/document-service';\n\ntype DocumentVersion = { documentId: string; locale: string };\ntype Knex = Parameters<Migration['up']>[0];\n\n/**\n * Check if the model has draft and publish enabled.\n */\nconst hasDraftAndPublish = async (trx: Knex, meta: any) => {\n const hasTable = await trx.schema.hasTable(meta.tableName);\n\n if (!hasTable) {\n return false;\n }\n\n const uid = meta.uid as UID.ContentType;\n const model = strapi.getModel(uid);\n const hasDP = contentTypes.hasDraftAndPublish(model);\n if (!hasDP) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Copy all the published entries to draft entries, without it's components, dynamic zones or relations.\n * This ensures all necessary draft's exist before copying it's relations.\n */\nasync function copyPublishedEntriesToDraft({\n db,\n trx,\n uid,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n}) {\n // Extract all scalar attributes to use in the insert query\n const meta = db.metadata.get(uid);\n\n // Get scalar attributes that will be copied over the new draft\n const scalarAttributes = Object.values(meta.attributes).reduce((acc, attribute: any) => {\n if (['id'].includes(attribute.columnName)) {\n return acc;\n }\n\n if (contentTypes.isScalarAttribute(attribute)) {\n acc.push(attribute.columnName);\n }\n\n return acc;\n }, [] as string[]);\n\n /**\n * Query to copy the published entries into draft entries.\n *\n * INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n * SELECT columnName1, columnName2, columnName3, ...\n * FROM tableName\n */\n await trx\n // INSERT INTO tableName (columnName1, columnName2, columnName3, ...)\n .into(\n trx.raw(`?? (${scalarAttributes.map(() => `??`).join(', ')})`, [\n meta.tableName,\n ...scalarAttributes,\n ])\n )\n .insert((subQb: typeof trx) => {\n // SELECT columnName1, columnName2, columnName3, ...\n subQb\n .select(\n ...scalarAttributes.map((att: string) => {\n // Override 'publishedAt' and 'updatedAt' attributes\n if (att === 'published_at') {\n return trx.raw('NULL as ??', 'published_at');\n }\n\n return att;\n })\n )\n .from(meta.tableName)\n // Only select entries that were published\n .whereNotNull('published_at');\n });\n}\n\n/**\n * Load a batch of versions to discard.\n *\n * Versions with only a draft version will be ignored.\n * Only versions with a published version (which always have a draft version) will be discarded.\n */\nexport async function* getBatchToDiscard({\n db,\n trx,\n uid,\n defaultBatchSize = 1000,\n}: {\n db: Database;\n trx: Knex;\n uid: string;\n defaultBatchSize?: number;\n}) {\n const client = db.config.connection.client;\n const isSQLite =\n typeof client === 'string' && ['sqlite', 'sqlite3', 'better-sqlite3'].includes(client);\n\n // The SQLite documentation states that the maximum number of terms in a\n // compound SELECT statement is 500 by default.\n // See: https://www.sqlite.org/limits.html\n // To ensure a successful migration, we limit the batch size to 500 for SQLite.\n const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;\n let offset = 0;\n let hasMore = true;\n\n while (hasMore) {\n // Look for the published entries to discard\n const batch: DocumentVersion[] = await db\n .queryBuilder(uid)\n .select(['id', 'documentId', 'locale'])\n .where({ publishedAt: { $ne: null } })\n .limit(batchSize)\n .offset(offset)\n .orderBy('id')\n .transacting(trx)\n .execute();\n\n if (batch.length < batchSize) {\n hasMore = false;\n }\n\n offset += batchSize;\n yield batch;\n }\n}\n\n/**\n * 2 pass migration to create the draft entries for all the published entries.\n * And then discard the drafts to copy the relations.\n */\nconst migrateUp = async (trx: Knex, db: Database) => {\n const dpModels = [];\n for (const meta of Array.from(db.metadata.values())) {\n const hasDP = await hasDraftAndPublish(trx, meta);\n if (hasDP) {\n dpModels.push(meta);\n }\n }\n\n /**\n * Create plain draft entries for all the entries that were published.\n */\n for (const model of dpModels) {\n await copyPublishedEntriesToDraft({ db, trx, uid: model.uid });\n }\n\n /**\n * Discard the drafts will copy the relations from the published entries to the newly created drafts.\n *\n * Load a batch of entries (batched to prevent loading millions of rows at once ),\n * and discard them using the document service.\n *\n * NOTE: This is using a custom document service without any validations,\n * to prevent the migration from failing if users already had invalid data in V4.\n * E.g. @see https://github.com/strapi/strapi/issues/21583\n */\n const documentService = createDocumentService(strapi, {\n async validateEntityCreation(_, data) {\n return data;\n },\n async validateEntityUpdate(_, data) {\n // Data can be partially empty on partial updates\n // This migration doesn't trigger any update (or partial update),\n // so it's safe to return the data as is.\n return data as any;\n },\n });\n\n for (const model of dpModels) {\n const discardDraft = async (entry: DocumentVersion) =>\n documentService(model.uid as UID.ContentType).discardDraft({\n documentId: entry.documentId,\n locale: entry.locale,\n });\n\n for await (const batch of getBatchToDiscard({ db, trx, uid: model.uid })) {\n // NOTE: concurrency had to be disabled to prevent a race condition with self-references\n // TODO: improve performance in a safe way\n await async.map(batch, discardDraft, { concurrency: 1 });\n }\n }\n};\n\nexport const discardDocumentDrafts: Migration = {\n name: 'core::5.0.0-discard-drafts',\n async up(trx, db) {\n await migrateUp(trx, db);\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["hasDraftAndPublish","trx","meta","hasTable","schema","tableName","uid","model","strapi","getModel","hasDP","contentTypes","copyPublishedEntriesToDraft","db","metadata","get","scalarAttributes","Object","values","attributes","reduce","acc","attribute","includes","columnName","isScalarAttribute","push","into","raw","map","join","insert","subQb","select","att","from","whereNotNull","getBatchToDiscard","defaultBatchSize","client","config","connection","isSQLite","batchSize","Math","min","offset","hasMore","batch","queryBuilder","where","publishedAt","$ne","limit","orderBy","transacting","execute","length","migrateUp","dpModels","Array","documentService","createDocumentService","validateEntityCreation","_","data","validateEntityUpdate","discardDraft","entry","documentId","locale","async","concurrency","discardDocumentDrafts","name","up","down","Error"],"mappings":";;;AAsBA;;IAGA,MAAMA,kBAAqB,GAAA,OAAOC,GAAWC,EAAAA,IAAAA,GAAAA;IAC3C,MAAMC,QAAAA,GAAW,MAAMF,GAAIG,CAAAA,MAAM,CAACD,QAAQ,CAACD,KAAKG,SAAS,CAAA;AAEzD,IAAA,IAAI,CAACF,QAAU,EAAA;QACb,OAAO,KAAA;AACT;IAEA,MAAMG,GAAAA,GAAMJ,KAAKI,GAAG;IACpB,MAAMC,KAAAA,GAAQC,MAAOC,CAAAA,QAAQ,CAACH,GAAAA,CAAAA;IAC9B,MAAMI,KAAAA,GAAQC,YAAaX,CAAAA,kBAAkB,CAACO,KAAAA,CAAAA;AAC9C,IAAA,IAAI,CAACG,KAAO,EAAA;QACV,OAAO,KAAA;AACT;IAEA,OAAO,IAAA;AACT,CAAA;AAEA;;;IAIA,eAAeE,4BAA4B,EACzCC,EAAE,EACFZ,GAAG,EACHK,GAAG,EAKJ,EAAA;;AAEC,IAAA,MAAMJ,IAAOW,GAAAA,EAAAA,CAAGC,QAAQ,CAACC,GAAG,CAACT,GAAAA,CAAAA;;IAG7B,MAAMU,gBAAAA,GAAmBC,MAAOC,CAAAA,MAAM,CAAChB,IAAAA,CAAKiB,UAAU,CAAEC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AKY,EAAAA,EAAAA,CAAAA;AACvB,KAAA;IACA,MAAM+D,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAM,CAAA,iBAAA,CAAA;AAClB;AACF;;;;"}
@@ -0,0 +1,4 @@
1
+ import { Input } from './draft-publish';
2
+ declare const enableFirstPublishedAt: ({ oldContentTypes, contentTypes }: Input) => Promise<void>;
3
+ export { enableFirstPublishedAt as enable };
4
+ //# sourceMappingURL=first-published-at.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"first-published-at.d.ts","sourceRoot":"","sources":["../../src/migrations/first-published-at.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAUxC,QAAA,MAAM,sBAAsB,sCAA6C,KAAK,kBA6D7E,CAAC;AAEF,OAAO,EAAE,sBAAsB,IAAI,MAAM,EAAE,CAAC"}