@strapi/core 0.0.0-experimental.04d28a073af6fa6a173e2212fa8593a4df25efbf → 0.0.0-experimental.16eaafeff6bd4cd49d56f3c31d002cad71a1134a

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 (152) hide show
  1. package/dist/Strapi.d.ts +3 -1
  2. package/dist/Strapi.d.ts.map +1 -1
  3. package/dist/Strapi.js +57 -13
  4. package/dist/Strapi.js.map +1 -1
  5. package/dist/Strapi.mjs +38 -13
  6. package/dist/Strapi.mjs.map +1 -1
  7. package/dist/core-api/controller/collection-type.d.ts.map +1 -1
  8. package/dist/core-api/controller/collection-type.js +2 -0
  9. package/dist/core-api/controller/collection-type.js.map +1 -1
  10. package/dist/core-api/controller/collection-type.mjs +2 -0
  11. package/dist/core-api/controller/collection-type.mjs.map +1 -1
  12. package/dist/core-api/controller/single-type.d.ts.map +1 -1
  13. package/dist/core-api/controller/single-type.js +1 -0
  14. package/dist/core-api/controller/single-type.js.map +1 -1
  15. package/dist/core-api/controller/single-type.mjs +1 -0
  16. package/dist/core-api/controller/single-type.mjs.map +1 -1
  17. package/dist/core-api/service/collection-type.d.ts +1 -7
  18. package/dist/core-api/service/collection-type.d.ts.map +1 -1
  19. package/dist/core-api/service/collection-type.js +5 -3
  20. package/dist/core-api/service/collection-type.js.map +1 -1
  21. package/dist/core-api/service/collection-type.mjs +6 -4
  22. package/dist/core-api/service/collection-type.mjs.map +1 -1
  23. package/dist/core-api/service/pagination.d.ts +4 -11
  24. package/dist/core-api/service/pagination.d.ts.map +1 -1
  25. package/dist/core-api/service/pagination.js +14 -40
  26. package/dist/core-api/service/pagination.js.map +1 -1
  27. package/dist/core-api/service/pagination.mjs +16 -42
  28. package/dist/core-api/service/pagination.mjs.map +1 -1
  29. package/dist/core-api/service/single-type.d.ts.map +1 -1
  30. package/dist/core-api/service/single-type.js +2 -1
  31. package/dist/core-api/service/single-type.js.map +1 -1
  32. package/dist/core-api/service/single-type.mjs +2 -1
  33. package/dist/core-api/service/single-type.mjs.map +1 -1
  34. package/dist/loaders/apis.d.ts.map +1 -1
  35. package/dist/loaders/apis.js +10 -10
  36. package/dist/loaders/apis.js.map +1 -1
  37. package/dist/loaders/apis.mjs +10 -10
  38. package/dist/loaders/apis.mjs.map +1 -1
  39. package/dist/loaders/plugins/get-enabled-plugins.d.ts.map +1 -1
  40. package/dist/loaders/plugins/get-enabled-plugins.js +5 -5
  41. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  42. package/dist/loaders/plugins/get-enabled-plugins.mjs +5 -5
  43. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  44. package/dist/middlewares/cors.d.ts.map +1 -1
  45. package/dist/middlewares/cors.js +6 -8
  46. package/dist/middlewares/cors.js.map +1 -1
  47. package/dist/middlewares/cors.mjs +6 -8
  48. package/dist/middlewares/cors.mjs.map +1 -1
  49. package/dist/middlewares/security.d.ts.map +1 -1
  50. package/dist/middlewares/security.js +10 -3
  51. package/dist/middlewares/security.js.map +1 -1
  52. package/dist/middlewares/security.mjs +11 -4
  53. package/dist/middlewares/security.mjs.map +1 -1
  54. package/dist/migrations/database/5.0.0-discard-drafts.d.ts +19 -1
  55. package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
  56. package/dist/migrations/database/5.0.0-discard-drafts.js +1 -0
  57. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  58. package/dist/migrations/database/5.0.0-discard-drafts.mjs +2 -1
  59. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  60. package/dist/migrations/draft-publish.d.ts.map +1 -1
  61. package/dist/migrations/draft-publish.js +14 -31
  62. package/dist/migrations/draft-publish.js.map +1 -1
  63. package/dist/migrations/draft-publish.mjs +15 -32
  64. package/dist/migrations/draft-publish.mjs.map +1 -1
  65. package/dist/services/document-service/entries.d.ts +1 -1
  66. package/dist/services/document-service/entries.d.ts.map +1 -1
  67. package/dist/services/document-service/entries.js +2 -1
  68. package/dist/services/document-service/entries.js.map +1 -1
  69. package/dist/services/document-service/entries.mjs +2 -1
  70. package/dist/services/document-service/entries.mjs.map +1 -1
  71. package/dist/services/document-service/events.d.ts +25 -0
  72. package/dist/services/document-service/events.d.ts.map +1 -0
  73. package/dist/services/document-service/events.js +47 -0
  74. package/dist/services/document-service/events.js.map +1 -0
  75. package/dist/services/document-service/events.mjs +47 -0
  76. package/dist/services/document-service/events.mjs.map +1 -0
  77. package/dist/services/document-service/index.d.ts.map +1 -1
  78. package/dist/services/document-service/index.js.map +1 -1
  79. package/dist/services/document-service/index.mjs.map +1 -1
  80. package/dist/services/document-service/internationalization.d.ts.map +1 -1
  81. package/dist/services/document-service/internationalization.js +14 -5
  82. package/dist/services/document-service/internationalization.js.map +1 -1
  83. package/dist/services/document-service/internationalization.mjs +14 -5
  84. package/dist/services/document-service/internationalization.mjs.map +1 -1
  85. package/dist/services/document-service/repository.d.ts.map +1 -1
  86. package/dist/services/document-service/repository.js +73 -45
  87. package/dist/services/document-service/repository.js.map +1 -1
  88. package/dist/services/document-service/repository.mjs +75 -47
  89. package/dist/services/document-service/repository.mjs.map +1 -1
  90. package/dist/services/document-service/transform/relations/extract/data-ids.d.ts.map +1 -1
  91. package/dist/services/document-service/transform/relations/extract/data-ids.js +3 -0
  92. package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
  93. package/dist/services/document-service/transform/relations/extract/data-ids.mjs +3 -0
  94. package/dist/services/document-service/transform/relations/extract/data-ids.mjs.map +1 -1
  95. package/dist/services/document-service/transform/relations/transform/data-ids.d.ts.map +1 -1
  96. package/dist/services/document-service/transform/relations/transform/data-ids.js +3 -0
  97. package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
  98. package/dist/services/document-service/transform/relations/transform/data-ids.mjs +3 -0
  99. package/dist/services/document-service/transform/relations/transform/data-ids.mjs.map +1 -1
  100. package/dist/services/document-service/transform/relations/utils/map-relation.d.ts.map +1 -1
  101. package/dist/services/document-service/transform/relations/utils/map-relation.js +7 -3
  102. package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
  103. package/dist/services/document-service/transform/relations/utils/map-relation.mjs +7 -3
  104. package/dist/services/document-service/transform/relations/utils/map-relation.mjs.map +1 -1
  105. package/dist/services/entity-validator/index.d.ts +14 -1
  106. package/dist/services/entity-validator/index.d.ts.map +1 -1
  107. package/dist/services/entity-validator/index.js +82 -20
  108. package/dist/services/entity-validator/index.js.map +1 -1
  109. package/dist/services/entity-validator/index.mjs +82 -20
  110. package/dist/services/entity-validator/index.mjs.map +1 -1
  111. package/dist/services/entity-validator/validators.d.ts +10 -8
  112. package/dist/services/entity-validator/validators.d.ts.map +1 -1
  113. package/dist/services/entity-validator/validators.js +60 -19
  114. package/dist/services/entity-validator/validators.js.map +1 -1
  115. package/dist/services/entity-validator/validators.mjs +53 -11
  116. package/dist/services/entity-validator/validators.mjs.map +1 -1
  117. package/dist/services/event-hub.d.ts +1 -0
  118. package/dist/services/event-hub.d.ts.map +1 -1
  119. package/dist/services/event-hub.js +9 -4
  120. package/dist/services/event-hub.js.map +1 -1
  121. package/dist/services/event-hub.mjs +9 -4
  122. package/dist/services/event-hub.mjs.map +1 -1
  123. package/dist/services/server/index.js +1 -1
  124. package/dist/services/server/index.js.map +1 -1
  125. package/dist/services/server/index.mjs +1 -1
  126. package/dist/services/server/index.mjs.map +1 -1
  127. package/dist/services/server/koa.d.ts.map +1 -1
  128. package/dist/services/server/koa.js +1 -1
  129. package/dist/services/server/koa.js.map +1 -1
  130. package/dist/services/server/koa.mjs +1 -1
  131. package/dist/services/server/koa.mjs.map +1 -1
  132. package/dist/services/webhook-runner.d.ts +2 -1
  133. package/dist/services/webhook-runner.d.ts.map +1 -1
  134. package/dist/services/webhook-runner.js.map +1 -1
  135. package/dist/services/webhook-runner.mjs.map +1 -1
  136. package/dist/services/webhook-store.d.ts +2 -8
  137. package/dist/services/webhook-store.d.ts.map +1 -1
  138. package/dist/services/webhook-store.js +9 -2
  139. package/dist/services/webhook-store.js.map +1 -1
  140. package/dist/services/webhook-store.mjs +9 -2
  141. package/dist/services/webhook-store.mjs.map +1 -1
  142. package/dist/utils/fetch.d.ts.map +1 -1
  143. package/dist/utils/fetch.js +4 -3
  144. package/dist/utils/fetch.js.map +1 -1
  145. package/dist/utils/fetch.mjs +4 -3
  146. package/dist/utils/fetch.mjs.map +1 -1
  147. package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
  148. package/dist/utils/transform-content-types-to-models.js +10 -0
  149. package/dist/utils/transform-content-types-to-models.js.map +1 -1
  150. package/dist/utils/transform-content-types-to-models.mjs +10 -0
  151. package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
  152. package/package.json +22 -18
@@ -1 +1 @@
1
- {"version":3,"file":"validators.js","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport strapiUtils from '@strapi/utils';\nimport type { Schema, Struct } from '@strapi/types';\nimport blocksValidator from './blocks-validator';\n\nconst { yup } = strapiUtils;\n\ninterface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n model: Struct.ContentTypeSchema;\n updatedAttribute: { name: string; value: unknown };\n entity: Record<string, unknown> | null;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: strapiUtils.yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: strapiUtils.yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: strapiUtils.yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\n/**\n * Adds unique validator\n */\nconst addUniqueValidator = <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n /**\n * At this point we know that we are creating a new entry, publishing an entry or that the unique field value has changed\n * We check if there is an entry of this content type in the same locale, publication state and with the same unique field value\n */\n const record = await strapi.db.query(model.uid).findOne({\n where: {\n locale: options.locale,\n publishedAt: options.isDraft ? null : { $notNull: true },\n [updatedAttribute.name]: value,\n ...(entity?.id ? { id: { $ne: entity.id } } : {}),\n },\n });\n\n return !record;\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(1, '${path} cannot be empty');\n};\n\nconst uidValidator = (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nconst enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nconst integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nconst datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport default {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["strapiUtils","_"],"mappings":";;;;;;;AAKA,MAAM,EAAE,IAAQ,IAAAA;AA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AAO,IAAW,CAAC;AACnF;AAEA,MAAM,mBAAmB,CACvB,OACA,YACG;AACH,MAAI,SAAS,IAAI,OAAO,EAAE,QAAQ;AAEzB,WAAA,uBAAuB,QAAQ,KAAK;AACpC,WAAA,uBAAuB,QAAQ,KAAK;AACpC,WAAA,mBAAmB,QAAQ,OAAO,OAAO;AAE3C,SAAA;AACT;AAEA,MAAM,iBAAiB,CACrB,OACA,YACG;AACC,MAAA,SAAS,IAAI;AACR,WAAA,qBAAqB,QAAQ,KAAK;AAClC,WAAA,qBAAqB,QAAQ,KAAK;AAClC,WAAA,mBAAmB,QAAQ,OAAO,OAAO;AAE3C,SAAA;AACT;AAEA,MAAM,sBAAsB,CAC1B,OACA,YACG;AACG,QAAA,SAAS,IAAI;AACZ,SAAA,mBAAmB,QAAQ,OAAO,OAAO;AAClD;AAEA,MAAM,iBAAiB,CACrB,OAMA,YACG;AACG,QAAA,SAAS,IAAI;AACZ,SAAA,mBAAmB,QAAQ,OAAO,OAAO;AAClD;AAEA,MAAe,aAAA;AAAA,EACb,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS,MAAM,IAAI,QAAQ;AAAA,EAC3B,KAAK;AAAA,EACL,MAAM,MAAM,IAAI,MAAM;AAAA,EACtB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AACV;;"}
1
+ {"version":3,"file":"validators.js","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport blocksValidator from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\ninterface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n model: Struct.ContentTypeSchema;\n updatedAttribute: { name: string; value: unknown };\n entity: Modules.EntityValidator.Entity;\n componentContext: ComponentContext;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\n/**\n * Adds unique validator\n */\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n let queryUid: string;\n let queryWhere: Record<string, any> = {};\n\n if (componentContext) {\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n queryUid = parentModel.uid;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n } else {\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n queryUid = model.uid;\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n };\n\n scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n queryWhere = scalarAttributeWhere;\n }\n\n // The validation should pass if there is no other record found from the query\n // TODO query not working for dynamic zones (type === relation)\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(1, '${path} cannot be empty');\n};\n\nconst uidValidator = (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nconst enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nconst integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nconst datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport default {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["_","value","yup"],"mappings":";;;;;;AAyBA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAaA,WAAE,QAAA,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAaA,mBAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGIA,WAAE,QAAA,SAAS,KAAK,GAAG,IAAI,UAAU,IAAIA,WAAAA,QAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGIA,WAAE,QAAA,SAAS,KAAK,GAAG,IAAI,UAAU,IAAIA,WAAAA,QAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,uBAAuB,CAC3B,WACA;AAAA,EACE;AACF,MAGIA,mBAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,KAAK,GAAG,IAAI;AAKvD,MAAM,uBAAuB,CAC3B,WACA;AAAA,EACE;AACF,MAGIA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3B,KAAK;AAAA,EACL,MAAM,MAAMA,YAAA,IAAI,MAAM;AAAA,EACtB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AACV;;"}
@@ -1,7 +1,6 @@
1
1
  import _ from "lodash";
2
- import strapiUtils from "@strapi/utils";
2
+ import { yup } from "@strapi/utils";
3
3
  import blocksValidator from "./blocks-validator.mjs";
4
- const { yup } = strapiUtils;
5
4
  const addMinLengthValidator = (validator, {
6
5
  attr
7
6
  }, { isDraft }) => {
@@ -33,7 +32,8 @@ const addUniqueValidator = (validator, {
33
32
  attr,
34
33
  model,
35
34
  updatedAttribute,
36
- entity
35
+ entity,
36
+ componentContext
37
37
  }, options) => {
38
38
  if (attr.type !== "uid" && !attr.unique) {
39
39
  return validator;
@@ -46,15 +46,57 @@ const addUniqueValidator = (validator, {
46
46
  if (!isPublish && value === entity?.[updatedAttribute.name]) {
47
47
  return true;
48
48
  }
49
- const record = await strapi.db.query(model.uid).findOne({
50
- where: {
51
- locale: options.locale,
52
- publishedAt: options.isDraft ? null : { $notNull: true },
53
- [updatedAttribute.name]: value,
54
- ...entity?.id ? { id: { $ne: entity.id } } : {}
49
+ let queryUid;
50
+ let queryWhere = {};
51
+ if (componentContext) {
52
+ const hasRepeatableData = componentContext.repeatableData.length > 0;
53
+ if (hasRepeatableData) {
54
+ const { name: updatedName, value: updatedValue } = updatedAttribute;
55
+ const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join(".");
56
+ const values = componentContext.repeatableData.map((item) => {
57
+ return pathToCheck.split(".").reduce((acc, key) => acc[key], item);
58
+ });
59
+ const isUpdatedAttributeRepeatedInThisEntity = values.filter((value2) => value2 === updatedValue).length > 1;
60
+ if (isUpdatedAttributeRepeatedInThisEntity) {
61
+ return false;
62
+ }
55
63
  }
56
- });
57
- return !record;
64
+ const {
65
+ model: parentModel,
66
+ options: parentOptions,
67
+ id: excludeId
68
+ } = componentContext.parentContent;
69
+ queryUid = parentModel.uid;
70
+ const whereConditions = {};
71
+ const isParentDraft = parentOptions && parentOptions.isDraft;
72
+ whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };
73
+ if (parentOptions?.locale) {
74
+ whereConditions.locale = parentOptions.locale;
75
+ }
76
+ if (excludeId && !Number.isNaN(excludeId)) {
77
+ whereConditions.id = { $ne: excludeId };
78
+ }
79
+ queryWhere = {
80
+ ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {
81
+ [updatedAttribute.name]: value
82
+ }),
83
+ ...whereConditions
84
+ };
85
+ } else {
86
+ queryUid = model.uid;
87
+ const scalarAttributeWhere = {
88
+ [updatedAttribute.name]: value
89
+ };
90
+ scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };
91
+ if (options?.locale) {
92
+ scalarAttributeWhere.locale = options.locale;
93
+ }
94
+ if (entity?.id) {
95
+ scalarAttributeWhere.id = { $ne: entity.id };
96
+ }
97
+ queryWhere = scalarAttributeWhere;
98
+ }
99
+ return !await strapi.db.query(queryUid).findOne({ where: queryWhere });
58
100
  });
59
101
  };
60
102
  const stringValidator = (metas, options) => {
@@ -1 +1 @@
1
- {"version":3,"file":"validators.mjs","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport strapiUtils from '@strapi/utils';\nimport type { Schema, Struct } from '@strapi/types';\nimport blocksValidator from './blocks-validator';\n\nconst { yup } = strapiUtils;\n\ninterface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n model: Struct.ContentTypeSchema;\n updatedAttribute: { name: string; value: unknown };\n entity: Record<string, unknown> | null;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: strapiUtils.yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: strapiUtils.yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: strapiUtils.yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: strapiUtils.yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\n/**\n * Adds unique validator\n */\nconst addUniqueValidator = <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n /**\n * At this point we know that we are creating a new entry, publishing an entry or that the unique field value has changed\n * We check if there is an entry of this content type in the same locale, publication state and with the same unique field value\n */\n const record = await strapi.db.query(model.uid).findOne({\n where: {\n locale: options.locale,\n publishedAt: options.isDraft ? null : { $notNull: true },\n [updatedAttribute.name]: value,\n ...(entity?.id ? { id: { $ne: entity.id } } : {}),\n },\n });\n\n return !record;\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(1, '${path} cannot be empty');\n};\n\nconst uidValidator = (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nconst enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nconst integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nconst datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport default {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":[],"mappings":";;;AAKA,MAAM,EAAE,IAAQ,IAAA;AAmBhB,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,uBAAuB,CAC3B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,KAAK,GAAG,IAAI;AAKvD,MAAM,uBAAuB,CAC3B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,KAAK,GAAG,IAAI;AAKvD,MAAM,0BAA0B,CAC9B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,WAAW,QAAQ,CAAC,EAAE,YAAY,KAAK,KAAK,IAC/C,UAAU,QAAQ,IAAI,OAAO,KAAK,KAAK,GA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js","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport blocksValidator from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\ninterface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n model: Struct.ContentTypeSchema;\n updatedAttribute: { name: string; value: unknown };\n entity: Modules.EntityValidator.Entity;\n componentContext: ComponentContext;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\n/**\n * Adds unique validator\n */\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n let queryUid: string;\n let queryWhere: Record<string, any> = {};\n\n if (componentContext) {\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n queryUid = parentModel.uid;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n } else {\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n queryUid = model.uid;\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n };\n\n scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n queryWhere = scalarAttributeWhere;\n }\n\n // The validation should pass if there is no other record found from the query\n // TODO query not working for dynamic zones (type === relation)\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(1, '${path} cannot be empty');\n};\n\nconst uidValidator = (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nconst enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nconst integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nconst datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport default {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["value"],"mappings":";;;AAyBA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,M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,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS,MAAM,IAAI,QAAQ;AAAA,EAC3B,KAAK;AAAA,EACL,MAAM,MAAM,IAAI,MAAM;AAAA,EACtB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AACV;"}
@@ -10,6 +10,7 @@ export interface EventHub {
10
10
  destroy(): EventHub;
11
11
  removeListener(eventName: string, listener: Listener): void;
12
12
  removeAllListeners(): EventHub;
13
+ removeAllSubscribers(): EventHub;
13
14
  addListener(eventName: string, listener: Listener): () => void;
14
15
  }
15
16
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"event-hub.d.ts","sourceRoot":"","sources":["../../src/services/event-hub.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAC9E,MAAM,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzD,MAAM,WAAW,QAAQ;IACvB,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,SAAS,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,IAAI,CAAC;IAC9C,WAAW,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IAC1C,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;IACtD,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,G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D,OAAO,IAAI,QAAQ,CAAC;IACpB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC5D,kBAAkB,IAAI,QAAQ,CAAC;IAC/B,oBAAoB,IAAI,QAAQ,CAAC;IACjC,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;CAChE;AAED;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,cAAc,IAAI,QAAQ,CA0FjD"}
@@ -38,7 +38,7 @@ function createEventHub() {
38
38
  };
39
39
  },
40
40
  off(eventName, listener) {
41
- listeners.get(eventName).splice(listeners.get(eventName).indexOf(listener), 1);
41
+ listeners.get(eventName)?.splice(listeners.get(eventName).indexOf(listener), 1);
42
42
  },
43
43
  once(eventName, listener) {
44
44
  return eventHub.on(eventName, async (...args) => {
@@ -47,15 +47,20 @@ function createEventHub() {
47
47
  });
48
48
  },
49
49
  destroy() {
50
- listeners.clear();
51
- subscribers.length = 0;
50
+ this.removeAllListeners();
51
+ this.removeAllSubscribers();
52
52
  return this;
53
53
  },
54
54
  removeListener(eventName, listener) {
55
55
  return eventHub.off(eventName, listener);
56
56
  },
57
57
  removeAllListeners() {
58
- return eventHub.destroy();
58
+ listeners.clear();
59
+ return this;
60
+ },
61
+ removeAllSubscribers() {
62
+ subscribers.length = 0;
63
+ return this;
59
64
  },
60
65
  addListener(eventName, listener) {
61
66
  return eventHub.on(eventName, listener);
@@ -1 +1 @@
1
- {"version":3,"file":"event-hub.js","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n for (const listener of listeners.get(eventName)) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n listeners.get(eventName).splice(listeners.get(eventName).indexOf(listener), 1);\n },\n\n once(eventName, listener) {\n return eventHub.on(eventName, async (...args) => {\n eventHub.off(eventName, listener);\n return listener(...args);\n });\n },\n\n destroy() {\n listeners.clear();\n subscribers.length = 0;\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n return eventHub.destroy();\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":[],"mappings":";AAmBA,SAAwB,iBAA2B;AAC3C,QAAA,gCAAgB;AAGhB,QAAA,oBAAoB,OAAO,cAAsB,SAAoB;A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A,eAAe,WAAW,UAAU;AAC3B,aAAA,SAAS,IAAI,WAAW,QAAQ;AAAA,IACzC;AAAA,IAEA,qBAAqB;AACnB,aAAO,SAAS;IAClB;AAAA,IAEA,YAAY,WAAW,UAAU;AACxB,aAAA,SAAS,GAAG,WAAW,QAAQ;AAAA,IACxC;AAAA,EAAA;AAGK,SAAA;AACT;;"}
1
+ {"version":3,"file":"event-hub.js","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n removeAllSubscribers(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n for (const listener of listeners.get(eventName)) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n listeners.get(eventName)?.splice(listeners.get(eventName).indexOf(listener), 1);\n },\n\n once(eventName, listener) {\n return eventHub.on(eventName, async (...args) => {\n eventHub.off(eventName, listener);\n return listener(...args);\n });\n },\n\n destroy() {\n this.removeAllListeners();\n this.removeAllSubscribers();\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n listeners.clear();\n return this;\n },\n\n removeAllSubscribers() {\n subscribers.length = 0;\n return this;\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":[],"mappings":";AAoBA,SAAwB,iBAA2B;AAC3C,QAAA,gCAAgB;AAGhB,QAAA,oBAAoB,OAAO,cAAsB,SAAoB;AACrE,QAAA,UAAU,IAAI,SAAS,GAAG;AAC5B,iBAAW,YAAY,UAAU,IAAI,SAAS,GAAG;AACzC,cAAA,SAAS,GAAG,IAAI;AAAA,MACxB;AAAA,IACF;AAAA,EAAA;AAII,QAAA,cAAc,CAAC,iBAAiB;AAEtC,QAAM,WAAqB;AAAA,IACzB,MAAM,KAAK,cAAc,MAAM;AAC7B,iBAAW,cAAc,aAAa;AAC9B,cAAA,WAAW,WAAW,GAAG,IAAI;AAAA,MACrC;AAAA,IACF;AAAA,IAEA,UAAU,YAAY;AACpB,kBAAY,KAAK,UAAU;AAG3B,aAAO,MAAM;AACX,iBAAS,YAAY,UAAU;AAAA,MAAA;AAAA,IAEnC;AAAA,IAEA,YAAY,YAAY;AAChB,YAAA,kBAAkB,YAAY,QAAQ,UAAU;AAGtD,UAAI,mBAAmB,GAAG;AACZ,oBAAA,OAAO,iBAAiB,CAAC;AAAA,MACvC;AAAA,IACF;AAAA,IAEA,GAAG,WAAW,UAAU;AACtB,UAAI,CAAC,UAAU,IAAI,SAAS,GAAG;AAC7B,kBAAU,IAAI,WAAW,CAAC,QAAQ,CAAC;AAAA,MAAA,OAC9B;AACL,kBAAU,IAAI,SAAS,EAAE,KAAK,QAAQ;AAAA,MACxC;AAGA,aAAO,MAAM;AACF,iBAAA,IAAI,WAAW,QAAQ;AAAA,MAAA;AAAA,IAEpC;AAAA,IAEA,IAAI,WAAW,UAAU;AACb,gBAAA,IAAI,SAAS,GAAG,OAAO,UAAU,IAAI,SAAS,EAAE,QAAQ,QAAQ,GAAG,CAAC;AAAA,IAChF;AAAA,IAEA,KAAK,WAAW,UAAU;AACxB,aAAO,SAAS,GAAG,WAAW,UAAU,SAAS;AACtC,iBAAA,IAAI,WAAW,QAAQ;AACzB,eAAA,SAAS,GAAG,IAAI;AAAA,MAAA,CACxB;AAAA,IACH;AAAA,IAEA,UAAU;AACR,WAAK,mBAAmB;AACxB,WAAK,qBAAqB;AACnB,aAAA;AAAA,IACT;AAAA,IAEA,eAAe,WAAW,UAAU;AAC3B,aAAA,SAAS,IAAI,WAAW,QAAQ;AAAA,IACzC;AAAA,IAEA,qBAAqB;AACnB,gBAAU,MAAM;AACT,aAAA;AAAA,IACT;AAAA,IAEA,uBAAuB;AACrB,kBAAY,SAAS;AACd,aAAA;AAAA,IACT;AAAA,IAEA,YAAY,WAAW,UAAU;AACxB,aAAA,SAAS,GAAG,WAAW,QAAQ;AAAA,IACxC;AAAA,EAAA;AAGK,SAAA;AACT;;"}
@@ -37,7 +37,7 @@ function createEventHub() {
37
37
  };
38
38
  },
39
39
  off(eventName, listener) {
40
- listeners.get(eventName).splice(listeners.get(eventName).indexOf(listener), 1);
40
+ listeners.get(eventName)?.splice(listeners.get(eventName).indexOf(listener), 1);
41
41
  },
42
42
  once(eventName, listener) {
43
43
  return eventHub.on(eventName, async (...args) => {
@@ -46,15 +46,20 @@ function createEventHub() {
46
46
  });
47
47
  },
48
48
  destroy() {
49
- listeners.clear();
50
- subscribers.length = 0;
49
+ this.removeAllListeners();
50
+ this.removeAllSubscribers();
51
51
  return this;
52
52
  },
53
53
  removeListener(eventName, listener) {
54
54
  return eventHub.off(eventName, listener);
55
55
  },
56
56
  removeAllListeners() {
57
- return eventHub.destroy();
57
+ listeners.clear();
58
+ return this;
59
+ },
60
+ removeAllSubscribers() {
61
+ subscribers.length = 0;
62
+ return this;
58
63
  },
59
64
  addListener(eventName, listener) {
60
65
  return eventHub.on(eventName, listener);
@@ -1 +1 @@
1
- {"version":3,"file":"event-hub.mjs","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n for (const listener of listeners.get(eventName)) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n listeners.get(eventName).splice(listeners.get(eventName).indexOf(listener), 1);\n },\n\n once(eventName, listener) {\n return eventHub.on(eventName, async (...args) => {\n eventHub.off(eventName, listener);\n return listener(...args);\n });\n },\n\n destroy() {\n listeners.clear();\n subscribers.length = 0;\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n return eventHub.destroy();\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":[],"mappings":"AAmBA,SAAwB,iBAA2B;AAC3C,QAAA,gCAAgB;AAGhB,QAAA,oBAAoB,OAAO,cAAsB,SAAoB;AACrE,QAAA,UAAU,IAAI,SAAS,GAAG;AAC5B,iBAAW,YAAY,UAAU,IAAI,SAAS,GAAG;AACzC,cAAA,SAAS,GAAG,IAAI;AAAA,MACxB;AAAA,IACF;AAAA,EAAA;AAII,QAAA,cAAc,CAAC,iBAAiB;AAEtC,QAAM,WAAqB;AAAA,IACzB,MAAM,KAAK,cAAc,MAAM;AAC7B,iBAAW,cAAc,aAAa;AAC9B,cAAA,WAAW,WAAW,GAAG,IAAI;AAAA,MACrC;AAAA,IACF;AAAA,IAEA,UAAU,YAAY;AACpB,kBAAY,KAAK,UAAU;AAG3B,aAAO,MAAM;AACX,iBAAS,YAAY,UAAU;AAAA,MAAA;AAAA,IAEnC;AAAA,IAEA,YAAY,YAAY;AAChB,YAAA,kBAAkB,YAAY,QAAQ,UAAU;AAGtD,UAAI,mBAAmB,GAAG;AACZ,oBAAA,OAAO,iBAAiB,CAAC;AAAA,MACvC;AAAA,IACF;AAAA,IAEA,GAAG,WAAW,UAAU;AACtB,UAAI,CAAC,UAAU,IAAI,SAAS,GAAG;AAC7B,kBAAU,IAAI,WAAW,CAAC,QAAQ,CAAC;AAAA,MAAA,OAC9B;AACL,kBAAU,IAAI,SAAS,EAAE,KAAK,QAAQ;AAAA,MACxC;AAGA,aAAO,MAAM;AACF,iBAAA,IAAI,WAAW,QAAQ;AAAA,MAAA;AAAA,IAEpC;AAAA,IAEA,IAAI,WAAW,UAAU;AACb,gBAAA,IAAI,SAAS,EAAE,OAAO,UAAU,IAAI,SAAS,EAAE,QAAQ,QAAQ,GAAG,CAAC;AAAA,IAC/E;AAAA,IAEA,KAAK,WAAW,UAAU;AACxB,aAAO,SAAS,GAAG,WAAW,UAAU,SAAS;AACtC,iBAAA,IAAI,WAAW,QAAQ;AACzB,eAAA,SAAS,GAAG,IAAI;AAAA,MAAA,CACxB;AAAA,IACH;AAAA,IAEA,UAAU;AACR,gBAAU,MAAM;AAChB,kBAAY,SAAS;AACd,aAAA;AAAA,IACT;AAAA,IAEA,eAAe,WAAW,UAAU;AAC3B,aAAA,SAAS,IAAI,WAAW,QAAQ;AAAA,IACzC;AAAA,IAEA,qBAAqB;AACnB,aAAO,SAAS;IAClB;AAAA,IAEA,YAAY,WAAW,UAAU;AACxB,aAAA,SAAS,GAAG,WAAW,QAAQ;AAAA,IACxC;AAAA,EAAA;AAGK,SAAA;AACT;"}
1
+ {"version":3,"file":"event-hub.mjs","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n removeAllSubscribers(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n for (const listener of listeners.get(eventName)) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n listeners.get(eventName)?.splice(listeners.get(eventName).indexOf(listener), 1);\n },\n\n once(eventName, listener) {\n return eventHub.on(eventName, async (...args) => {\n eventHub.off(eventName, listener);\n return listener(...args);\n });\n },\n\n destroy() {\n this.removeAllListeners();\n this.removeAllSubscribers();\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n listeners.clear();\n return this;\n },\n\n removeAllSubscribers() {\n subscribers.length = 0;\n return this;\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":[],"mappings":"AAoBA,SAAwB,iBAA2B;AAC3C,QAAA,gCAAgB;AAGhB,QAAA,oBAAoB,OAAO,cAAsB,SAAoB;AACrE,QAAA,UAAU,IAAI,SAAS,GAAG;AAC5B,iBAAW,YAAY,UAAU,IAAI,SAAS,GAAG;AACzC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,qBAAqB;AACnB,gBAAU,MAAM;AACT,aAAA;AAAA,IACT;AAAA,IAEA,uBAAuB;AACrB,kBAAY,SAAS;AACd,aAAA;AAAA,IACT;AAAA,IAEA,YAAY,WAAW,UAAU;AACxB,aAAA,SAAS,GAAG,WAAW,QAAQ;AAAA,IACxC;AAAA,EAAA;AAGK,SAAA;AACT;"}
@@ -17,7 +17,7 @@ const healthCheck = async (ctx) => {
17
17
  };
18
18
  const createServer = (strapi) => {
19
19
  const app = koa({
20
- proxy: strapi.config.get("server.proxy"),
20
+ proxy: strapi.config.get("server.proxy.koa"),
21
21
  keys: strapi.config.get("server.app.keys")
22
22
  });
23
23
  app.use((ctx, next) => requestContext.run(ctx, () => next()));
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/services/server/index.ts"],"sourcesContent":["import Router from '@koa/router';\nimport type { Core, Modules } from '@strapi/types';\n\nimport { createHTTPServer } from './http-server';\nimport { createRouteManager } from './routing';\nimport { createAdminAPI } from './admin-api';\nimport { createContentAPI } from './content-api';\nimport registerAllRoutes from './register-routes';\nimport registerApplicationMiddlewares from './register-middlewares';\nimport createKoaApp from './koa';\nimport requestCtx from '../request-context';\n\nconst healthCheck: Core.MiddlewareHandler = async (ctx) => {\n ctx.set('strapi', 'You are so French!');\n ctx.status = 204;\n};\n\nconst createServer = (strapi: Core.Strapi): Modules.Server.Server => {\n const app = createKoaApp({\n proxy: strapi.config.get('server.proxy'),\n keys: strapi.config.get('server.app.keys'),\n });\n\n app.use((ctx, next) => requestCtx.run(ctx, () => next()));\n\n const router = new Router();\n\n const routeManager = createRouteManager(strapi);\n\n const httpServer = createHTTPServer(strapi, app);\n\n const apis = {\n 'content-api': createContentAPI(strapi),\n admin: createAdminAPI(strapi),\n };\n\n // init health check\n router.all('/_health', healthCheck);\n\n const state = {\n mounted: false,\n };\n\n return {\n app,\n router,\n httpServer,\n\n api(name) {\n return apis[name];\n },\n\n use(...args) {\n app.use(...args);\n return this;\n },\n\n routes(routes: Core.Router | Omit<Core.Route, 'info'>[]) {\n if (!Array.isArray(routes) && routes.type) {\n const api = apis[routes.type];\n if (!api) {\n throw new Error(`API ${routes.type} not found. Possible APIs are ${Object.keys(apis)}`);\n }\n\n apis[routes.type].routes(routes);\n return this;\n }\n\n routeManager.addRoutes(routes, router);\n return this;\n },\n\n mount() {\n state.mounted = true;\n\n Object.values(apis).forEach((api) => api.mount(router));\n app.use(router.routes()).use(router.allowedMethods());\n\n return this;\n },\n\n initRouting() {\n registerAllRoutes(strapi);\n\n return this;\n },\n\n async initMiddlewares() {\n await registerApplicationMiddlewares(strapi);\n\n return this;\n },\n\n listRoutes() {\n return [...router.stack];\n },\n\n listen(...args: any[]) {\n if (!state.mounted) {\n this.mount();\n }\n\n return httpServer.listen(...args);\n },\n\n async destroy() {\n await httpServer.destroy();\n },\n };\n};\n\nexport { createServer };\n"],"names":["createKoaApp","requestCtx","Router","createRouteManager","httpServer","createHTTPServer","createContentAPI","createAdminAPI","registerAllRoutes","registerApplicationMiddlewares"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,cAAsC,OAAO,QAAQ;AACrD,MAAA,IAAI,UAAU,oBAAoB;AACtC,MAAI,SAAS;AACf;AAEM,MAAA,eAAe,CAAC,WAA+C;AACnE,QAAM,MAAMA,IAAa;AAAA,IACvB,OAAO,OAAO,OAAO,IAAI,cAAc;AAAA,IACvC,MAAM,OAAO,OAAO,IAAI,iBAAiB;AAAA,EAAA,CAC1C;AAEG,MAAA,IAAI,CAAC,KAAK,SAASC,eAAW,IAAI,KAAK,MAAM,KAAM,CAAA,CAAC;AAElD,QAAA,SAAS,IAAIC,gBAAAA;AAEb,QAAA,eAAeC,2BAAmB,MAAM;AAExC,QAAAC,eAAaC,WAAAA,iBAAiB,QAAQ,GAAG;AAE/C,QAAM,OAAO;AAAA,IACX,eAAeC,4BAAiB,MAAM;AAAA,IACtC,OAAOC,wBAAe,MAAM;AAAA,EAAA;AAIvB,SAAA,IAAI,YAAY,WAAW;AAEl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server/index.ts"],"sourcesContent":["import Router from '@koa/router';\nimport type { Core, Modules } from '@strapi/types';\n\nimport { createHTTPServer } from './http-server';\nimport { createRouteManager } from './routing';\nimport { createAdminAPI } from './admin-api';\nimport { createContentAPI } from './content-api';\nimport registerAllRoutes from './register-routes';\nimport registerApplicationMiddlewares from './register-middlewares';\nimport createKoaApp from './koa';\nimport requestCtx from '../request-context';\n\nconst healthCheck: Core.MiddlewareHandler = async (ctx) => {\n ctx.set('strapi', 'You are so French!');\n ctx.status = 204;\n};\n\nconst createServer = (strapi: Core.Strapi): Modules.Server.Server => {\n const app = createKoaApp({\n proxy: strapi.config.get('server.proxy.koa'),\n keys: strapi.config.get('server.app.keys'),\n });\n\n app.use((ctx, next) => requestCtx.run(ctx, () => next()));\n\n const router = new Router();\n\n const routeManager = createRouteManager(strapi);\n\n const httpServer = createHTTPServer(strapi, app);\n\n const apis = {\n 'content-api': createContentAPI(strapi),\n admin: createAdminAPI(strapi),\n };\n\n // init health check\n router.all('/_health', healthCheck);\n\n const state = {\n mounted: false,\n };\n\n return {\n app,\n router,\n httpServer,\n\n api(name) {\n return apis[name];\n },\n\n use(...args) {\n app.use(...args);\n return this;\n },\n\n routes(routes: Core.Router | Omit<Core.Route, 'info'>[]) {\n if (!Array.isArray(routes) && routes.type) {\n const api = apis[routes.type];\n if (!api) {\n throw new Error(`API ${routes.type} not found. Possible APIs are ${Object.keys(apis)}`);\n }\n\n apis[routes.type].routes(routes);\n return this;\n }\n\n routeManager.addRoutes(routes, router);\n return this;\n },\n\n mount() {\n state.mounted = true;\n\n Object.values(apis).forEach((api) => api.mount(router));\n app.use(router.routes()).use(router.allowedMethods());\n\n return this;\n },\n\n initRouting() {\n registerAllRoutes(strapi);\n\n return this;\n },\n\n async initMiddlewares() {\n await registerApplicationMiddlewares(strapi);\n\n return this;\n },\n\n listRoutes() {\n return [...router.stack];\n },\n\n listen(...args: any[]) {\n if (!state.mounted) {\n this.mount();\n }\n\n return httpServer.listen(...args);\n },\n\n async destroy() {\n await httpServer.destroy();\n },\n };\n};\n\nexport { createServer };\n"],"names":["createKoaApp","requestCtx","Router","createRouteManager","httpServer","createHTTPServer","createContentAPI","createAdminAPI","registerAllRoutes","registerApplicationMiddlewares"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,cAAsC,OAAO,QAAQ;AACrD,MAAA,IAAI,UAAU,oBAAoB;AACtC,MAAI,SAAS;AACf;AAEM,MAAA,eAAe,CAAC,WAA+C;AACnE,QAAM,MAAMA,IAAa;AAAA,IACvB,OAAO,OAAO,OAAO,IAAI,kBAAkB;AAAA,IAC3C,MAAM,OAAO,OAAO,IAAI,iBAAiB;AAAA,EAAA,CAC1C;AAEG,MAAA,IAAI,CAAC,KAAK,SAASC,eAAW,IAAI,KAAK,MAAM,KAAM,CAAA,CAAC;AAElD,QAAA,SAAS,IAAIC,gBAAAA;AAEb,QAAA,eAAeC,2BAAmB,MAAM;AAExC,QAAAC,eAAaC,WAAAA,iBAAiB,QAAQ,GAAG;AAE/C,QAAM,OAAO;AAAA,IACX,eAAeC,4BAAiB,MAAM;AAAA,IACtC,OAAOC,wBAAe,MAAM;AAAA,EAAA;AAIvB,SAAA,IAAI,YAAY,WAAW;AAElC,QAAM,QAAQ;AAAA,IACZ,SAAS;AAAA,EAAA;AAGJ,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IAAA,YACAH;AAAAA,IAEA,IAAI,MAAM;AACR,aAAO,KAAK,IAAI;AAAA,IAClB;AAAA,IAEA,OAAO,MAAM;AACP,UAAA,IAAI,GAAG,IAAI;AACR,aAAA;AAAA,IACT;AAAA,IAEA,OAAO,QAAkD;AACvD,UAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,MAAM;AACnC,cAAA,MAAM,KAAK,OAAO,IAAI;AAC5B,YAAI,CAAC,KAAK;AACF,gBAAA,IAAI,MAAM,OAAO,OAAO,IAAI,iCAAiC,OAAO,KAAK,IAAI,CAAC,EAAE;AAAA,QACxF;AAEA,aAAK,OAAO,IAAI,EAAE,OAAO,MAAM;AACxB,eAAA;AAAA,MACT;AAEa,mBAAA,UAAU,QAAQ,MAAM;AAC9B,aAAA;AAAA,IACT;AAAA,IAEA,QAAQ;AACN,YAAM,UAAU;AAET,aAAA,OAAO,IAAI,EAAE,QAAQ,CAAC,QAAQ,IAAI,MAAM,MAAM,CAAC;AAClD,UAAA,IAAI,OAAO,OAAO,CAAC,EAAE,IAAI,OAAO,gBAAgB;AAE7C,aAAA;AAAA,IACT;AAAA,IAEA,cAAc;AACZI,qBAAkB,MAAM;AAEjB,aAAA;AAAA,IACT;AAAA,IAEA,MAAM,kBAAkB;AACtB,YAAMC,oBAA+B,MAAM;AAEpC,aAAA;AAAA,IACT;AAAA,IAEA,aAAa;AACJ,aAAA,CAAC,GAAG,OAAO,KAAK;AAAA,IACzB;AAAA,IAEA,UAAU,MAAa;AACjB,UAAA,CAAC,MAAM,SAAS;AAClB,aAAK,MAAM;AAAA,MACb;AAEO,aAAAL,aAAW,OAAO,GAAG,IAAI;AAAA,IAClC;AAAA,IAEA,MAAM,UAAU;AACd,YAAMA,aAAW;IACnB;AAAA,EAAA;AAEJ;;"}
@@ -13,7 +13,7 @@ const healthCheck = async (ctx) => {
13
13
  };
14
14
  const createServer = (strapi) => {
15
15
  const app = createKoaApp({
16
- proxy: strapi.config.get("server.proxy"),
16
+ proxy: strapi.config.get("server.proxy.koa"),
17
17
  keys: strapi.config.get("server.app.keys")
18
18
  });
19
19
  app.use((ctx, next) => requestCtx.run(ctx, () => next()));
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../src/services/server/index.ts"],"sourcesContent":["import Router from '@koa/router';\nimport type { Core, Modules } from '@strapi/types';\n\nimport { createHTTPServer } from './http-server';\nimport { createRouteManager } from './routing';\nimport { createAdminAPI } from './admin-api';\nimport { createContentAPI } from './content-api';\nimport registerAllRoutes from './register-routes';\nimport registerApplicationMiddlewares from './register-middlewares';\nimport createKoaApp from './koa';\nimport requestCtx from '../request-context';\n\nconst healthCheck: Core.MiddlewareHandler = async (ctx) => {\n ctx.set('strapi', 'You are so French!');\n ctx.status = 204;\n};\n\nconst createServer = (strapi: Core.Strapi): Modules.Server.Server => {\n const app = createKoaApp({\n proxy: strapi.config.get('server.proxy'),\n keys: strapi.config.get('server.app.keys'),\n });\n\n app.use((ctx, next) => requestCtx.run(ctx, () => next()));\n\n const router = new Router();\n\n const routeManager = createRouteManager(strapi);\n\n const httpServer = createHTTPServer(strapi, app);\n\n const apis = {\n 'content-api': createContentAPI(strapi),\n admin: createAdminAPI(strapi),\n };\n\n // init health check\n router.all('/_health', healthCheck);\n\n const state = {\n mounted: false,\n };\n\n return {\n app,\n router,\n httpServer,\n\n api(name) {\n return apis[name];\n },\n\n use(...args) {\n app.use(...args);\n return this;\n },\n\n routes(routes: Core.Router | Omit<Core.Route, 'info'>[]) {\n if (!Array.isArray(routes) && routes.type) {\n const api = apis[routes.type];\n if (!api) {\n throw new Error(`API ${routes.type} not found. Possible APIs are ${Object.keys(apis)}`);\n }\n\n apis[routes.type].routes(routes);\n return this;\n }\n\n routeManager.addRoutes(routes, router);\n return this;\n },\n\n mount() {\n state.mounted = true;\n\n Object.values(apis).forEach((api) => api.mount(router));\n app.use(router.routes()).use(router.allowedMethods());\n\n return this;\n },\n\n initRouting() {\n registerAllRoutes(strapi);\n\n return this;\n },\n\n async initMiddlewares() {\n await registerApplicationMiddlewares(strapi);\n\n return this;\n },\n\n listRoutes() {\n return [...router.stack];\n },\n\n listen(...args: any[]) {\n if (!state.mounted) {\n this.mount();\n }\n\n return httpServer.listen(...args);\n },\n\n async destroy() {\n await httpServer.destroy();\n },\n };\n};\n\nexport { createServer };\n"],"names":[],"mappings":";;;;;;;;;AAYA,MAAM,cAAsC,OAAO,QAAQ;AACrD,MAAA,IAAI,UAAU,oBAAoB;AACtC,MAAI,SAAS;AACf;AAEM,MAAA,eAAe,CAAC,WAA+C;AACnE,QAAM,MAAM,aAAa;AAAA,IACvB,OAAO,OAAO,OAAO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AAM,kBAAkB;AACtB,YAAM,+BAA+B,MAAM;AAEpC,aAAA;AAAA,IACT;AAAA,IAEA,aAAa;AACJ,aAAA,CAAC,GAAG,OAAO,KAAK;AAAA,IACzB;AAAA,IAEA,UAAU,MAAa;AACjB,UAAA,CAAC,MAAM,SAAS;AAClB,aAAK,MAAM;AAAA,MACb;AAEO,aAAA,WAAW,OAAO,GAAG,IAAI;AAAA,IAClC;AAAA,IAEA,MAAM,UAAU;AACd,YAAM,WAAW;IACnB;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../src/services/server/index.ts"],"sourcesContent":["import Router from '@koa/router';\nimport type { Core, Modules } from '@strapi/types';\n\nimport { createHTTPServer } from './http-server';\nimport { createRouteManager } from './routing';\nimport { createAdminAPI } from './admin-api';\nimport { createContentAPI } from './content-api';\nimport registerAllRoutes from './register-routes';\nimport registerApplicationMiddlewares from './register-middlewares';\nimport createKoaApp from './koa';\nimport requestCtx from '../request-context';\n\nconst healthCheck: Core.MiddlewareHandler = async (ctx) => {\n ctx.set('strapi', 'You are so French!');\n ctx.status = 204;\n};\n\nconst createServer = (strapi: Core.Strapi): Modules.Server.Server => {\n const app = createKoaApp({\n proxy: strapi.config.get('server.proxy.koa'),\n keys: strapi.config.get('server.app.keys'),\n });\n\n app.use((ctx, next) => requestCtx.run(ctx, () => next()));\n\n const router = new Router();\n\n const routeManager = createRouteManager(strapi);\n\n const httpServer = createHTTPServer(strapi, app);\n\n const apis = {\n 'content-api': createContentAPI(strapi),\n admin: createAdminAPI(strapi),\n };\n\n // init health check\n router.all('/_health', healthCheck);\n\n const state = {\n mounted: false,\n };\n\n return {\n app,\n router,\n httpServer,\n\n api(name) {\n return apis[name];\n },\n\n use(...args) {\n app.use(...args);\n return this;\n },\n\n routes(routes: Core.Router | Omit<Core.Route, 'info'>[]) {\n if (!Array.isArray(routes) && routes.type) {\n const api = apis[routes.type];\n if (!api) {\n throw new Error(`API ${routes.type} not found. Possible APIs are ${Object.keys(apis)}`);\n }\n\n apis[routes.type].routes(routes);\n return this;\n }\n\n routeManager.addRoutes(routes, router);\n return this;\n },\n\n mount() {\n state.mounted = true;\n\n Object.values(apis).forEach((api) => api.mount(router));\n app.use(router.routes()).use(router.allowedMethods());\n\n return this;\n },\n\n initRouting() {\n registerAllRoutes(strapi);\n\n return this;\n },\n\n async initMiddlewares() {\n await registerApplicationMiddlewares(strapi);\n\n return this;\n },\n\n listRoutes() {\n return [...router.stack];\n },\n\n listen(...args: any[]) {\n if (!state.mounted) {\n this.mount();\n }\n\n return httpServer.listen(...args);\n },\n\n async destroy() {\n await httpServer.destroy();\n },\n };\n};\n\nexport { createServer };\n"],"names":[],"mappings":";;;;;;;;;AAYA,MAAM,cAAsC,OAAO,QAAQ;AACrD,MAAA,IAAI,UAAU,oBAAoB;AACtC,MAAI,SAAS;AACf;AAEM,MAAA,eAAe,CAAC,WAA+C;AACnE,QAAM,MAAM,aAAa;AAAA,IACvB,OAAO,OAAO,OAAO,IAAI,kBAAkB;AAAA,IAC3C,MAAM,OAAO,OAAO,IAAI,iBAAiB;AAAA,EAAA,CAC1C;AAEG,MAAA,IAAI,CAAC,KAAK,SAAS,WAAW,IAAI,KAAK,MAAM,KAAM,CAAA,CAAC;AAElD,QAAA,SAAS,IAAI;AAEb,QAAA,eAAe,mBAAmB,MAAM;AAExC,QAAA,aAAa,iBAAiB,QAAQ,GAAG;AAE/C,QAAM,OAAO;AAAA,IACX,eAAe,iBAAiB,MAAM;AAAA,IACtC,OAAO,eAAe,MAAM;AAAA,EAAA;AAIvB,SAAA,IAAI,YAAY,WAAW;AAElC,QAAM,QAAQ;AAAA,IACZ,SAAS;AAAA,EAAA;AAGJ,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IAEA,IAAI,MAAM;AACR,aAAO,KAAK,IAAI;AAAA,IAClB;AAAA,IAEA,OAAO,MAAM;AACP,UAAA,IAAI,GAAG,IAAI;AACR,aAAA;AAAA,IACT;AAAA,IAE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CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;QAC7B,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;QAC7B,eAAe,EAAE,OAAO,CAAC;QACzB,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;KAC7D;CACF;AA6CD,QAAA,MAAM,YAAY,oBAAqB;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,8CAOxE,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"koa.d.ts","sourceRoot":"","sources":["../../../src/services/server/koa.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,MAAM,KAAK,CAAC;AAMtB,OAAO,QAAQ,KAAK,CAAC;IACnB,UAAU,YAAY;QACpB,IAAI,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;QAC3C,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;QAC7B,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;QAC7B,eAAe,EAAE,OAAO,CAAC;QACzB,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;KAC7D;CACF;AA8CD,QAAA,MAAM,YAAY,oBAAqB;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,8CAOxE,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -15,7 +15,7 @@ const addCustomMethods = (app) => {
15
15
  statuses__default.default.codes.filter((code) => code >= 400 && code < 600).forEach((code) => {
16
16
  const name = statuses__default.default(code);
17
17
  const camelCasedName = _.camelCase(name);
18
- app.response[camelCasedName] = function responseCode(message, details = {}) {
18
+ app.response[camelCasedName] = function responseCode(message = name, details = {}) {
19
19
  const httpError = createError__default.default(code, message, { details });
20
20
  const { status, body } = errors.formatHttpError(httpError);
21
21
  this.status = status;
@@ -1 +1 @@
1
- {"version":3,"file":"koa.js","sources":["../../../src/services/server/koa.ts"],"sourcesContent":["import { isNil, camelCase } from 'lodash/fp';\nimport Koa from 'koa';\nimport createError from 'http-errors';\nimport delegate from 'delegates';\nimport statuses from 'statuses';\nimport { formatHttpError } from '../errors';\n\ndeclare module 'koa' {\n interface BaseResponse {\n send: (data: any, status?: number) => void;\n created: (data: any) => void;\n deleted: (data: any) => void;\n _explicitStatus: boolean;\n [key: string]: (message: string, details?: unknown) => void;\n }\n}\n\nconst addCustomMethods = (app: Koa) => {\n const delegator = delegate(app.context, 'response');\n\n /* errors */\n statuses.codes\n .filter((code) => code >= 400 && code < 600)\n .forEach((code) => {\n const name = statuses(code);\n const camelCasedName = camelCase(name);\n app.response[camelCasedName] = function responseCode(message, details = {}) {\n const httpError = createError(code, message, { details });\n const { status, body } = formatHttpError(httpError);\n this.status = status;\n this.body = body;\n };\n delegator.method(camelCasedName);\n });\n\n /* send, created, deleted */\n app.response.send = function send(data, status = 200) {\n this.status = status;\n this.body = data;\n };\n\n app.response.created = function created(data) {\n this.status = 201;\n this.body = data;\n };\n\n app.response.deleted = function deleted(data) {\n if (isNil(data)) {\n this.status = 204;\n } else {\n this.status = 200;\n this.body = data;\n }\n };\n\n delegator.method('send').method('created').method('deleted');\n\n return app;\n};\n\nconst createKoaApp = ({ proxy, keys }: { proxy: boolean; keys: string[] }) => {\n const app = new Koa({ proxy });\n app.keys = keys;\n\n addCustomMethods(app);\n\n return app;\n};\n\nexport default createKoaApp;\n"],"names":["delegate","statuses","camelCase","createError","formatHttpError","isNil","Koa"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,mBAAmB,CAAC,QAAa;AACrC,QAAM,YAAYA,kBAAA,QAAS,IAAI,SAAS,UAAU;AAGzCC,oBAAAA,QAAA,MACN,OAAO,CAAC,SAAS,QAAQ,OAAO,OAAO,GAAG,EAC1C,QAAQ,CAAC,SAAS;AACX,UAAA,OAAOA,0BAAS,IAAI;AACpB,UAAA,iBAAiBC,YAAU,IAAI;AACjC,QAAA,SAAS,cAAc,IAAI,SAAS,aAAa,SAAS,UAAU,IAAI;AAC1E,YAAM,YAAYC,qBAAAA,QAAY,MAAM,SAAS,EAAE,SAAS;AACxD,YAAM,EAAE,QAAQ,KAAK,IAAIC,uBAAgB,SAAS;AAClD,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IAAA;AAEd,cAAU,OAAO,cAAc;AAAA,EAAA,CAChC;AAGH,MAAI,SAAS,OAAO,SAAS,KAAK,MAAM,SAAS,KAAK;AACpD,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AAC5C,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AACxC,QAAAC,EAAAA,MAAM,IAAI,GAAG;AACf,WAAK,SAAS;AAAA,IAAA,OACT;AACL,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IACd;AAAA,EAAA;AAGF,YAAU,OAAO,MAAM,EAAE,OAAO,SAAS,EAAE,OAAO,SAAS;AAEpD,SAAA;AACT;AAEA,MAAM,eAAe,CAAC,EAAE,OAAO,WAA+C;AAC5E,QAAM,MAAM,IAAIC,aAAAA,QAAI,EAAE,MAAO,CAAA;AAC7B,MAAI,OAAO;AAEX,mBAAiB,GAAG;AAEb,SAAA;AACT;;"}
1
+ {"version":3,"file":"koa.js","sources":["../../../src/services/server/koa.ts"],"sourcesContent":["import { isNil, camelCase } from 'lodash/fp';\nimport Koa from 'koa';\nimport createError from 'http-errors';\nimport delegate from 'delegates';\nimport statuses from 'statuses';\nimport { formatHttpError } from '../errors';\n\ndeclare module 'koa' {\n interface BaseResponse {\n send: (data: any, status?: number) => void;\n created: (data: any) => void;\n deleted: (data: any) => void;\n _explicitStatus: boolean;\n [key: string]: (message: string, details?: unknown) => void;\n }\n}\n\nconst addCustomMethods = (app: Koa) => {\n const delegator = delegate(app.context, 'response');\n\n /* errors */\n statuses.codes\n .filter((code) => code >= 400 && code < 600)\n .forEach((code) => {\n const name = statuses(code);\n\n const camelCasedName = camelCase(name);\n app.response[camelCasedName] = function responseCode(message = name, details = {}) {\n const httpError = createError(code, message, { details });\n const { status, body } = formatHttpError(httpError);\n this.status = status;\n this.body = body;\n };\n delegator.method(camelCasedName);\n });\n\n /* send, created, deleted */\n app.response.send = function send(data, status = 200) {\n this.status = status;\n this.body = data;\n };\n\n app.response.created = function created(data) {\n this.status = 201;\n this.body = data;\n };\n\n app.response.deleted = function deleted(data) {\n if (isNil(data)) {\n this.status = 204;\n } else {\n this.status = 200;\n this.body = data;\n }\n };\n\n delegator.method('send').method('created').method('deleted');\n\n return app;\n};\n\nconst createKoaApp = ({ proxy, keys }: { proxy: boolean; keys: string[] }) => {\n const app = new Koa({ proxy });\n app.keys = keys;\n\n addCustomMethods(app);\n\n return app;\n};\n\nexport default createKoaApp;\n"],"names":["delegate","statuses","camelCase","createError","formatHttpError","isNil","Koa"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,mBAAmB,CAAC,QAAa;AACrC,QAAM,YAAYA,kBAAA,QAAS,IAAI,SAAS,UAAU;AAGzCC,oBAAAA,QAAA,MACN,OAAO,CAAC,SAAS,QAAQ,OAAO,OAAO,GAAG,EAC1C,QAAQ,CAAC,SAAS;AACX,UAAA,OAAOA,0BAAS,IAAI;AAEpB,UAAA,iBAAiBC,YAAU,IAAI;AACjC,QAAA,SAAS,cAAc,IAAI,SAAS,aAAa,UAAU,MAAM,UAAU,IAAI;AACjF,YAAM,YAAYC,qBAAAA,QAAY,MAAM,SAAS,EAAE,SAAS;AACxD,YAAM,EAAE,QAAQ,KAAK,IAAIC,uBAAgB,SAAS;AAClD,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IAAA;AAEd,cAAU,OAAO,cAAc;AAAA,EAAA,CAChC;AAGH,MAAI,SAAS,OAAO,SAAS,KAAK,MAAM,SAAS,KAAK;AACpD,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AAC5C,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AACxC,QAAAC,EAAAA,MAAM,IAAI,GAAG;AACf,WAAK,SAAS;AAAA,IAAA,OACT;AACL,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IACd;AAAA,EAAA;AAGF,YAAU,OAAO,MAAM,EAAE,OAAO,SAAS,EAAE,OAAO,SAAS;AAEpD,SAAA;AACT;AAEA,MAAM,eAAe,CAAC,EAAE,OAAO,WAA+C;AAC5E,QAAM,MAAM,IAAIC,aAAAA,QAAI,EAAE,MAAO,CAAA;AAC7B,MAAI,OAAO;AAEX,mBAAiB,GAAG;AAEb,SAAA;AACT;;"}
@@ -9,7 +9,7 @@ const addCustomMethods = (app) => {
9
9
  statuses.codes.filter((code) => code >= 400 && code < 600).forEach((code) => {
10
10
  const name = statuses(code);
11
11
  const camelCasedName = camelCase(name);
12
- app.response[camelCasedName] = function responseCode(message, details = {}) {
12
+ app.response[camelCasedName] = function responseCode(message = name, details = {}) {
13
13
  const httpError = createError(code, message, { details });
14
14
  const { status, body } = formatHttpError(httpError);
15
15
  this.status = status;
@@ -1 +1 @@
1
- {"version":3,"file":"koa.mjs","sources":["../../../src/services/server/koa.ts"],"sourcesContent":["import { isNil, camelCase } from 'lodash/fp';\nimport Koa from 'koa';\nimport createError from 'http-errors';\nimport delegate from 'delegates';\nimport statuses from 'statuses';\nimport { formatHttpError } from '../errors';\n\ndeclare module 'koa' {\n interface BaseResponse {\n send: (data: any, status?: number) => void;\n created: (data: any) => void;\n deleted: (data: any) => void;\n _explicitStatus: boolean;\n [key: string]: (message: string, details?: unknown) => void;\n }\n}\n\nconst addCustomMethods = (app: Koa) => {\n const delegator = delegate(app.context, 'response');\n\n /* errors */\n statuses.codes\n .filter((code) => code >= 400 && code < 600)\n .forEach((code) => {\n const name = statuses(code);\n const camelCasedName = camelCase(name);\n app.response[camelCasedName] = function responseCode(message, details = {}) {\n const httpError = createError(code, message, { details });\n const { status, body } = formatHttpError(httpError);\n this.status = status;\n this.body = body;\n };\n delegator.method(camelCasedName);\n });\n\n /* send, created, deleted */\n app.response.send = function send(data, status = 200) {\n this.status = status;\n this.body = data;\n };\n\n app.response.created = function created(data) {\n this.status = 201;\n this.body = data;\n };\n\n app.response.deleted = function deleted(data) {\n if (isNil(data)) {\n this.status = 204;\n } else {\n this.status = 200;\n this.body = data;\n }\n };\n\n delegator.method('send').method('created').method('deleted');\n\n return app;\n};\n\nconst createKoaApp = ({ proxy, keys }: { proxy: boolean; keys: string[] }) => {\n const app = new Koa({ proxy });\n app.keys = keys;\n\n addCustomMethods(app);\n\n return app;\n};\n\nexport default createKoaApp;\n"],"names":[],"mappings":";;;;;;AAiBA,MAAM,mBAAmB,CAAC,QAAa;AACrC,QAAM,YAAY,SAAS,IAAI,SAAS,UAAU;AAGzC,WAAA,MACN,OAAO,CAAC,SAAS,QAAQ,OAAO,OAAO,GAAG,EAC1C,QAAQ,CAAC,SAAS;AACX,UAAA,OAAO,SAAS,IAAI;AACpB,UAAA,iBAAiB,UAAU,IAAI;AACjC,QAAA,SAAS,cAAc,IAAI,SAAS,aAAa,SAAS,UAAU,IAAI;AAC1E,YAAM,YAAY,YAAY,MAAM,SAAS,EAAE,SAAS;AACxD,YAAM,EAAE,QAAQ,KAAK,IAAI,gBAAgB,SAAS;AAClD,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IAAA;AAEd,cAAU,OAAO,cAAc;AAAA,EAAA,CAChC;AAGH,MAAI,SAAS,OAAO,SAAS,KAAK,MAAM,SAAS,KAAK;AACpD,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AAC5C,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AACxC,QAAA,MAAM,IAAI,GAAG;AACf,WAAK,SAAS;AAAA,IAAA,OACT;AACL,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IACd;AAAA,EAAA;AAGF,YAAU,OAAO,MAAM,EAAE,OAAO,SAAS,EAAE,OAAO,SAAS;AAEpD,SAAA;AACT;AAEA,MAAM,eAAe,CAAC,EAAE,OAAO,WAA+C;AAC5E,QAAM,MAAM,IAAI,IAAI,EAAE,MAAO,CAAA;AAC7B,MAAI,OAAO;AAEX,mBAAiB,GAAG;AAEb,SAAA;AACT;"}
1
+ {"version":3,"file":"koa.mjs","sources":["../../../src/services/server/koa.ts"],"sourcesContent":["import { isNil, camelCase } from 'lodash/fp';\nimport Koa from 'koa';\nimport createError from 'http-errors';\nimport delegate from 'delegates';\nimport statuses from 'statuses';\nimport { formatHttpError } from '../errors';\n\ndeclare module 'koa' {\n interface BaseResponse {\n send: (data: any, status?: number) => void;\n created: (data: any) => void;\n deleted: (data: any) => void;\n _explicitStatus: boolean;\n [key: string]: (message: string, details?: unknown) => void;\n }\n}\n\nconst addCustomMethods = (app: Koa) => {\n const delegator = delegate(app.context, 'response');\n\n /* errors */\n statuses.codes\n .filter((code) => code >= 400 && code < 600)\n .forEach((code) => {\n const name = statuses(code);\n\n const camelCasedName = camelCase(name);\n app.response[camelCasedName] = function responseCode(message = name, details = {}) {\n const httpError = createError(code, message, { details });\n const { status, body } = formatHttpError(httpError);\n this.status = status;\n this.body = body;\n };\n delegator.method(camelCasedName);\n });\n\n /* send, created, deleted */\n app.response.send = function send(data, status = 200) {\n this.status = status;\n this.body = data;\n };\n\n app.response.created = function created(data) {\n this.status = 201;\n this.body = data;\n };\n\n app.response.deleted = function deleted(data) {\n if (isNil(data)) {\n this.status = 204;\n } else {\n this.status = 200;\n this.body = data;\n }\n };\n\n delegator.method('send').method('created').method('deleted');\n\n return app;\n};\n\nconst createKoaApp = ({ proxy, keys }: { proxy: boolean; keys: string[] }) => {\n const app = new Koa({ proxy });\n app.keys = keys;\n\n addCustomMethods(app);\n\n return app;\n};\n\nexport default createKoaApp;\n"],"names":[],"mappings":";;;;;;AAiBA,MAAM,mBAAmB,CAAC,QAAa;AACrC,QAAM,YAAY,SAAS,IAAI,SAAS,UAAU;AAGzC,WAAA,MACN,OAAO,CAAC,SAAS,QAAQ,OAAO,OAAO,GAAG,EAC1C,QAAQ,CAAC,SAAS;AACX,UAAA,OAAO,SAAS,IAAI;AAEpB,UAAA,iBAAiB,UAAU,IAAI;AACjC,QAAA,SAAS,cAAc,IAAI,SAAS,aAAa,UAAU,MAAM,UAAU,IAAI;AACjF,YAAM,YAAY,YAAY,MAAM,SAAS,EAAE,SAAS;AACxD,YAAM,EAAE,QAAQ,KAAK,IAAI,gBAAgB,SAAS;AAClD,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IAAA;AAEd,cAAU,OAAO,cAAc;AAAA,EAAA,CAChC;AAGH,MAAI,SAAS,OAAO,SAAS,KAAK,MAAM,SAAS,KAAK;AACpD,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AAC5C,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AACxC,QAAA,MAAM,IAAI,GAAG;AACf,WAAK,SAAS;AAAA,IAAA,OACT;AACL,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IACd;AAAA,EAAA;AAGF,YAAU,OAAO,MAAM,EAAE,OAAO,SAAS,EAAE,OAAO,SAAS;AAEpD,SAAA;AACT;AAEA,MAAM,eAAe,CAAC,EAAE,OAAO,WAA+C;AAC5E,QAAM,MAAM,IAAI,IAAI,EAAE,MAAO,CAAA;AAC7B,MAAI,OAAO;AAEX,mBAAiB,GAAG;AAEb,SAAA;AACT;"}
@@ -2,9 +2,10 @@
2
2
  * The event hub is Strapi's event control center.
3
3
  */
4
4
  import type { Logger } from '@strapi/logger';
5
- import type { Webhook } from './webhook-store';
5
+ import type { Modules } from '@strapi/types';
6
6
  import type { EventHub } from './event-hub';
7
7
  import type { Fetch } from '../utils/fetch';
8
+ type Webhook = Modules.WebhookStore.Webhook;
8
9
  interface ConstructorParameters {
9
10
  eventHub: EventHub;
10
11
  logger: Logger;
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-runner.d.ts","sourceRoot":"","sources":["../../src/services/webhook-runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAG7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAM5C,UAAU,qBAAqB;IAC7B,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACxC,KAAK,EAAE,KAAK,CAAC;CACd;AAED,UAAU,KAAK;IACb,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC/B;AAUD,cAAM,aAAa;IACjB,OAAO,CAAC,QAAQ,CAAW;IAE3B,OAAO,CAAC,MAAM,CAAS;IAEvB,OAAO,CAAC,MAAM,CAAS;IAEvB,OAAO,CAAC,WAAW,CAAqC;IAExD,OAAO,CAAC,SAAS,CAAoC;IAErD,OAAO,CAAC,KAAK,CAA2B;IAExC,OAAO,CAAC,KAAK,CAAQ;gBAET,EAAE,Q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M,aAAa;IACjB,OAAO,CAAC,QAAQ,CAAW;IAE3B,OAAO,CAAC,MAAM,CAAS;IAEvB,OAAO,CAAC,MAAM,CAAS;IAEvB,OAAO,CAAC,WAAW,CAAqC;IAExD,OAAO,CAAC,SAAS,CAAoC;IAErD,OAAO,CAAC,KAAK,CAA2B;IAExC,OAAO,CAAC,KAAK,CAAQ;gBAET,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAkB,EAAE,KAAK,EAAE,EAAE,qBAAqB;IAmBlF,cAAc,CAAC,KAAK,EAAE,MAAM;IAW5B,cAAc,CAAC,KAAK,EAAE,MAAM;IAgBtB,eAAe,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,KAAK;IAa5C,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,KAAK;;;;;;;;;;IAsC9C,GAAG,CAAC,OAAO,EAAE,OAAO;IAcpB,MAAM,CAAC,OAAO,EAAE,OAAO;IAMvB,MAAM,CAAC,OAAO,EAAE,OAAO;CAexB;AAED;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,mBAAmB,CAAC,IAAI,EAAE,qBAAqB,GAAG,aAAa,CAEtF;AAED,YAAY,EAAE,aAAa,EAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-runner.js","sources":["../../src/services/webhook-runner.ts"],"sourcesContent":["/**\n * The event hub is Strapi's event control center.\n */\n\nimport createdDebugger from 'debug';\nimport _ from 'lodash';\nimport type { Logger } from '@strapi/logger';\n\nimport WorkerQueue from './worker-queue';\nimport type { Webhook } from './webhook-store';\nimport type { EventHub } from './event-hub';\nimport type { Fetch } from '../utils/fetch';\n\ninterface Config {\n defaultHeaders: Record<string, string>;\n}\n\ninterface ConstructorParameters {\n eventHub: EventHub;\n logger: Logger;\n configuration?: Record<string, unknown>;\n fetch: Fetch;\n}\n\ninterface Event {\n event: string;\n info: Record<string, unknown>;\n}\n\ntype Listener = (info: Record<string, unknown>) => Promise<void>;\n\nconst debug = createdDebugger('strapi:webhook');\n\nconst defaultConfiguration: Config = {\n defaultHeaders: {},\n};\n\nclass WebhookRunner {\n private eventHub: EventHub;\n\n private logger: Logger;\n\n private config: Config;\n\n private webhooksMap: Map<string, Webhook[]> = new Map();\n\n private listeners: Map<string, Listener> = new Map();\n\n private queue: WorkerQueue<Event, void>;\n\n private fetch: Fetch;\n\n constructor({ eventHub, logger, configuration = {}, fetch }: ConstructorParameters) {\n debug('Initialized webhook runner');\n this.eventHub = eventHub;\n this.logger = logger;\n this.fetch = fetch;\n\n if (typeof configuration !== 'object') {\n throw new Error(\n 'Invalid configuration provided to the webhookRunner.\\nCheck your server.json -> webhooks configuration'\n );\n }\n\n this.config = _.merge(defaultConfiguration, configuration);\n\n this.queue = new WorkerQueue({ logger, concurrency: 5 });\n\n this.queue.subscribe(this.executeListener.bind(this));\n }\n\n deleteListener(event: string) {\n debug(`Deleting listener for event '${event}'`);\n\n const fn = this.listeners.get(event);\n\n if (fn !== undefined) {\n this.eventHub.off(event, fn);\n this.listeners.delete(event);\n }\n }\n\n createListener(event: string) {\n debug(`Creating listener for event '${event}'`);\n if (this.listeners.has(event)) {\n this.logger.error(\n `The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`\n );\n }\n\n const listen = async (info: Event['info']) => {\n this.queue.enqueue({ event, info });\n };\n\n this.listeners.set(event, listen);\n this.eventHub.on(event, listen);\n }\n\n async executeListener({ event, info }: Event) {\n debug(`Executing webhook for event '${event}'`);\n const webhooks = this.webhooksMap.get(event) || [];\n const activeWebhooks = webhooks.filter((webhook) => webhook.isEnabled === true);\n\n for (const webhook of activeWebhooks) {\n await this.run(webhook, event, info).catch((error: unknown) => {\n this.logger.error('Error running webhook');\n this.logger.error(error);\n });\n }\n }\n\n run(webhook: Webhook, event: string, info = {}) {\n const { url, headers } = webhook;\n\n return this.fetch(url, {\n method: 'post',\n body: JSON.stringify({\n event,\n createdAt: new Date(),\n ...info,\n }),\n headers: {\n ...this.config.defaultHeaders,\n ...headers,\n 'X-Strapi-Event': event,\n 'Content-Type': 'application/json',\n },\n signal: AbortSignal.timeout(10000),\n })\n .then(async (res) => {\n if (res.ok) {\n return {\n statusCode: res.status,\n };\n }\n\n return {\n statusCode: res.status,\n message: await res.text(),\n };\n })\n .catch((err) => {\n return {\n statusCode: 500,\n message: err.message,\n };\n });\n }\n\n add(webhook: Webhook) {\n debug(`Registering webhook '${webhook.id}'`);\n const { events } = webhook;\n\n events.forEach((event) => {\n if (this.webhooksMap.has(event)) {\n this.webhooksMap.get(event)?.push(webhook);\n } else {\n this.webhooksMap.set(event, [webhook]);\n this.createListener(event);\n }\n });\n }\n\n update(webhook: Webhook) {\n debug(`Refreshing webhook '${webhook.id}'`);\n this.remove(webhook);\n this.add(webhook);\n }\n\n remove(webhook: Webhook) {\n debug(`Unregistering webhook '${webhook.id}'`);\n\n this.webhooksMap.forEach((webhooks, event) => {\n const filteredWebhooks = webhooks.filter((value) => value.id !== webhook.id);\n\n // Cleanup hanging listeners\n if (filteredWebhooks.length === 0) {\n this.webhooksMap.delete(event);\n this.deleteListener(event);\n } else {\n this.webhooksMap.set(event, filteredWebhooks);\n }\n });\n }\n}\n\n/**\n * Expose a factory function instead of the class\n */\nexport default function createWebhookRunner(opts: ConstructorParameters): WebhookRunner {\n return new WebhookRunner(opts);\n}\n\nexport type { WebhookRunner };\n"],"names":["createdDebugger","_","WorkerQueue"],"mappings":";;;;;;;AA+BA,MAAM,QAAQA,wBAAAA,QAAgB,gBAAgB;AAE9C,MAAM,uBAA+B;AAAA,EACnC,gBAAgB,CAAC;AACnB;AAEA,MAAM,cAAc;AAAA,EACV;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,kCAA0C;EAE1C,gCAAuC;EAEvC;AAAA,EAEA;AAAA,EAER,YAAY,EAAE,UAAU,QAAQ,gBAAgB,CAAA,GAAI,SAAgC;AAClF,UAAM,4BAA4B;AAClC,SAAK,WAAW;AAChB,SAAK,SAAS;AACd,SA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AA,0BAA0B,QAAQ,EAAE,GAAG;AAE7C,SAAK,YAAY,QAAQ,CAAC,UAAU,UAAU;AACtC,YAAA,mBAAmB,SAAS,OAAO,CAAC,UAAU,MAAM,OAAO,QAAQ,EAAE;AAGvE,UAAA,iBAAiB,WAAW,GAAG;AAC5B,aAAA,YAAY,OAAO,KAAK;AAC7B,aAAK,eAAe,KAAK;AAAA,MAAA,OACpB;AACA,aAAA,YAAY,IAAI,OAAO,gBAAgB;AAAA,MAC9C;AAAA,IAAA,CACD;AAAA,EACH;AACF;AAKA,SAAwB,oBAAoB,MAA4C;AAC/E,SAAA,IAAI,cAAc,IAAI;AAC/B;;"}
1
+ {"version":3,"file":"webhook-runner.js","sources":["../../src/services/webhook-runner.ts"],"sourcesContent":["/**\n * The event hub is Strapi's event control center.\n */\n\nimport createdDebugger from 'debug';\nimport _ from 'lodash';\nimport type { Logger } from '@strapi/logger';\n\nimport type { Modules } from '@strapi/types';\nimport WorkerQueue from './worker-queue';\nimport type { EventHub } from './event-hub';\nimport type { Fetch } from '../utils/fetch';\n\ntype Webhook = Modules.WebhookStore.Webhook;\n\ninterface Config {\n defaultHeaders: Record<string, string>;\n}\n\ninterface ConstructorParameters {\n eventHub: EventHub;\n logger: Logger;\n configuration?: Record<string, unknown>;\n fetch: Fetch;\n}\n\ninterface Event {\n event: string;\n info: Record<string, unknown>;\n}\n\ntype Listener = (info: Record<string, unknown>) => Promise<void>;\n\nconst debug = createdDebugger('strapi:webhook');\n\nconst defaultConfiguration: Config = {\n defaultHeaders: {},\n};\n\nclass WebhookRunner {\n private eventHub: EventHub;\n\n private logger: Logger;\n\n private config: Config;\n\n private webhooksMap: Map<string, Webhook[]> = new Map();\n\n private listeners: Map<string, Listener> = new Map();\n\n private queue: WorkerQueue<Event, void>;\n\n private fetch: Fetch;\n\n constructor({ eventHub, logger, configuration = {}, fetch }: ConstructorParameters) {\n debug('Initialized webhook runner');\n this.eventHub = eventHub;\n this.logger = logger;\n this.fetch = fetch;\n\n if (typeof configuration !== 'object') {\n throw new Error(\n 'Invalid configuration provided to the webhookRunner.\\nCheck your server.json -> webhooks configuration'\n );\n }\n\n this.config = _.merge(defaultConfiguration, configuration);\n\n this.queue = new WorkerQueue({ logger, concurrency: 5 });\n\n this.queue.subscribe(this.executeListener.bind(this));\n }\n\n deleteListener(event: string) {\n debug(`Deleting listener for event '${event}'`);\n\n const fn = this.listeners.get(event);\n\n if (fn !== undefined) {\n this.eventHub.off(event, fn);\n this.listeners.delete(event);\n }\n }\n\n createListener(event: string) {\n debug(`Creating listener for event '${event}'`);\n if (this.listeners.has(event)) {\n this.logger.error(\n `The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`\n );\n }\n\n const listen = async (info: Event['info']) => {\n this.queue.enqueue({ event, info });\n };\n\n this.listeners.set(event, listen);\n this.eventHub.on(event, listen);\n }\n\n async executeListener({ event, info }: Event) {\n debug(`Executing webhook for event '${event}'`);\n const webhooks = this.webhooksMap.get(event) || [];\n const activeWebhooks = webhooks.filter((webhook) => webhook.isEnabled === true);\n\n for (const webhook of activeWebhooks) {\n await this.run(webhook, event, info).catch((error: unknown) => {\n this.logger.error('Error running webhook');\n this.logger.error(error);\n });\n }\n }\n\n run(webhook: Webhook, event: string, info = {}) {\n const { url, headers } = webhook;\n\n return this.fetch(url, {\n method: 'post',\n body: JSON.stringify({\n event,\n createdAt: new Date(),\n ...info,\n }),\n headers: {\n ...this.config.defaultHeaders,\n ...headers,\n 'X-Strapi-Event': event,\n 'Content-Type': 'application/json',\n },\n signal: AbortSignal.timeout(10000),\n })\n .then(async (res) => {\n if (res.ok) {\n return {\n statusCode: res.status,\n };\n }\n\n return {\n statusCode: res.status,\n message: await res.text(),\n };\n })\n .catch((err) => {\n return {\n statusCode: 500,\n message: err.message,\n };\n });\n }\n\n add(webhook: Webhook) {\n debug(`Registering webhook '${webhook.id}'`);\n const { events } = webhook;\n\n events.forEach((event) => {\n if (this.webhooksMap.has(event)) {\n this.webhooksMap.get(event)?.push(webhook);\n } else {\n this.webhooksMap.set(event, [webhook]);\n this.createListener(event);\n }\n });\n }\n\n update(webhook: Webhook) {\n debug(`Refreshing webhook '${webhook.id}'`);\n this.remove(webhook);\n this.add(webhook);\n }\n\n remove(webhook: Webhook) {\n debug(`Unregistering webhook '${webhook.id}'`);\n\n this.webhooksMap.forEach((webhooks, event) => {\n const filteredWebhooks = webhooks.filter((value) => value.id !== webhook.id);\n\n // Cleanup hanging listeners\n if (filteredWebhooks.length === 0) {\n this.webhooksMap.delete(event);\n this.deleteListener(event);\n } else {\n this.webhooksMap.set(event, filteredWebhooks);\n }\n });\n }\n}\n\n/**\n * Expose a factory function instead of the class\n */\nexport default function createWebhookRunner(opts: ConstructorParameters): WebhookRunner {\n return new WebhookRunner(opts);\n}\n\nexport type { WebhookRunner };\n"],"names":["createdDebugger","_","WorkerQueue"],"mappings":";;;;;;;AAiCA,MAAM,QAAQA,wBAAAA,QAAgB,gBAAgB;AAE9C,MAAM,uBAA+B;AAAA,EACnC,gBAAgB,CAAC;AACnB;AAEA,MAAM,cAAc;AAAA,EACV;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,kCAA0C;EAE1C,gCAAuC;EAEvC;AAAA,EAEA;AAAA,EAER,YAAY,EAAE,UAAU,QAAQ,gBAAgB,CAAA,GAAI,SAAgC;AAClF,UAAM,4BAA4B;AAClC,SAAK,WAAW;AAChB,SAAK,SAAS;AACd,SAAK,QAAQ;AAET,QAAA,OAAO,kBAAkB,UAAU;AACrC,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAAA,IAEJ;AAEA,SAAK,SAASC,WAAA,QAAE,MAAM,sBAAsB,aAAa;AAEzD,SAAK,QAAQ,IAAIC,YAAY,EAAE,QAAQ,aAAa,GAAG;AAEvD,SAAK,MAAM,UAAU,KAAK,gBAAgB,KAAK,IAAI,CAAC;AAAA,EACtD;AAAA,EAEA,eAAe,OAAe;AACtB,UAAA,gCAAgC,KAAK,GAAG;AAE9C,UAAM,KAAK,KAAK,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,MAA4C;AAC/E,SAAA,IAAI,cAAc,IAAI;AAC/B;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-runner.mjs","sources":["../../src/services/webhook-runner.ts"],"sourcesContent":["/**\n * The event hub is Strapi's event control center.\n */\n\nimport createdDebugger from 'debug';\nimport _ from 'lodash';\nimport type { Logger } from '@strapi/logger';\n\nimport WorkerQueue from './worker-queue';\nimport type { Webhook } from './webhook-store';\nimport type { EventHub } from './event-hub';\nimport type { Fetch } from '../utils/fetch';\n\ninterface Config {\n defaultHeaders: Record<string, string>;\n}\n\ninterface ConstructorParameters {\n eventHub: EventHub;\n logger: Logger;\n configuration?: Record<string, unknown>;\n fetch: Fetch;\n}\n\ninterface Event {\n event: string;\n info: Record<string, unknown>;\n}\n\ntype Listener = (info: Record<string, unknown>) => Promise<void>;\n\nconst debug = createdDebugger('strapi:webhook');\n\nconst defaultConfiguration: Config = {\n defaultHeaders: {},\n};\n\nclass WebhookRunner {\n private eventHub: EventHub;\n\n private logger: Logger;\n\n private config: Config;\n\n private webhooksMap: Map<string, Webhook[]> = new Map();\n\n private listeners: Map<string, Listener> = new Map();\n\n private queue: WorkerQueue<Event, void>;\n\n private fetch: Fetch;\n\n constructor({ eventHub, logger, configuration = {}, fetch }: ConstructorParameters) {\n debug('Initialized webhook runner');\n this.eventHub = eventHub;\n this.logger = logger;\n this.fetch = fetch;\n\n if (typeof configuration !== 'object') {\n throw new Error(\n 'Invalid configuration provided to the webhookRunner.\\nCheck your server.json -> webhooks configuration'\n );\n }\n\n this.config = _.merge(defaultConfiguration, configuration);\n\n this.queue = new WorkerQueue({ logger, concurrency: 5 });\n\n this.queue.subscribe(this.executeListener.bind(this));\n }\n\n deleteListener(event: string) {\n debug(`Deleting listener for event '${event}'`);\n\n const fn = this.listeners.get(event);\n\n if (fn !== undefined) {\n this.eventHub.off(event, fn);\n this.listeners.delete(event);\n }\n }\n\n createListener(event: string) {\n debug(`Creating listener for event '${event}'`);\n if (this.listeners.has(event)) {\n this.logger.error(\n `The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`\n );\n }\n\n const listen = async (info: Event['info']) => {\n this.queue.enqueue({ event, info });\n };\n\n this.listeners.set(event, listen);\n this.eventHub.on(event, listen);\n }\n\n async executeListener({ event, info }: Event) {\n debug(`Executing webhook for event '${event}'`);\n const webhooks = this.webhooksMap.get(event) || [];\n const activeWebhooks = webhooks.filter((webhook) => webhook.isEnabled === true);\n\n for (const webhook of activeWebhooks) {\n await this.run(webhook, event, info).catch((error: unknown) => {\n this.logger.error('Error running webhook');\n this.logger.error(error);\n });\n }\n }\n\n run(webhook: Webhook, event: string, info = {}) {\n const { url, headers } = webhook;\n\n return this.fetch(url, {\n method: 'post',\n body: JSON.stringify({\n event,\n createdAt: new Date(),\n ...info,\n }),\n headers: {\n ...this.config.defaultHeaders,\n ...headers,\n 'X-Strapi-Event': event,\n 'Content-Type': 'application/json',\n },\n signal: AbortSignal.timeout(10000),\n })\n .then(async (res) => {\n if (res.ok) {\n return {\n statusCode: res.status,\n };\n }\n\n return {\n statusCode: res.status,\n message: await res.text(),\n };\n })\n .catch((err) => {\n return {\n statusCode: 500,\n message: err.message,\n };\n });\n }\n\n add(webhook: Webhook) {\n debug(`Registering webhook '${webhook.id}'`);\n const { events } = webhook;\n\n events.forEach((event) => {\n if (this.webhooksMap.has(event)) {\n this.webhooksMap.get(event)?.push(webhook);\n } else {\n this.webhooksMap.set(event, [webhook]);\n this.createListener(event);\n }\n });\n }\n\n update(webhook: Webhook) {\n debug(`Refreshing webhook '${webhook.id}'`);\n this.remove(webhook);\n this.add(webhook);\n }\n\n remove(webhook: Webhook) {\n debug(`Unregistering webhook '${webhook.id}'`);\n\n this.webhooksMap.forEach((webhooks, event) => {\n const filteredWebhooks = webhooks.filter((value) => value.id !== webhook.id);\n\n // Cleanup hanging listeners\n if (filteredWebhooks.length === 0) {\n this.webhooksMap.delete(event);\n this.deleteListener(event);\n } else {\n this.webhooksMap.set(event, filteredWebhooks);\n }\n });\n }\n}\n\n/**\n * Expose a factory function instead of the class\n */\nexport default function createWebhookRunner(opts: ConstructorParameters): WebhookRunner {\n return new WebhookRunner(opts);\n}\n\nexport type { WebhookRunner };\n"],"names":["createdDebugger"],"mappings":";;;AA+BA,MAAM,QAAQA,eAAgB,gBAAgB;AAE9C,MAAM,uBAA+B;AAAA,EACnC,gBAAgB,CAAC;AACnB;AAEA,MAAM,cAAc;AAAA,EACV;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,kCAA0C;EAE1C,gCAAuC;EAEvC;AAAA,EAEA;AAAA,EAER,YAAY,EAAE,UAAU,QAAQ,gBAAgB,CAAA,GAAI,SAAgC;AAClF,UAAM,4BAA4B;AAClC,SAAK,WAAW;AAChB,SAAK,SAAS;AACd,SAAK,QAAQ;AAET,QAAA,OAAO,kBAAkB,UAAU;AACrC,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAAA,IAEJ;AAEA,SAAK,SAAS,EAAE,MAAM,sBAAsB,aAAa;AAEzD,SAAK,QAAQ,IAAI,YAAY,EAAE,QAAQ,aAAa,GAAG;AAEvD,SAAK,MAAM,UAAU,KAAK,gBAAgB,KAAK,IAAI,CAAC;AAAA,EACtD;AAAA,EAEA,eAAe,OAAe;AACtB,UAAA,gCAAgC,KAAK,GAAG;AAE9C,UAAM,KAAK,KAAK,UAAU,IAAI,KAAK;AAEnC,QAAI,OAAO,QAAW;AACf,WAAA,SAAS,IAAI,OAAO,EAAE;AACtB,WAAA,UAAU,OAAO,KAAK;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,eAAe,OAAe;AACtB,UAAA,gCAAgC,KAAK,GAAG;AAC9C,QAAI,KAAK,UAAU,IAAI,KAAK,GAAG;AAC7B,WAAK,OAAO;AAAA,QACV,0DAA0D,KAAK;AAAA,MAAA;AAAA,IAEnE;AAEM,UAAA,SAAS,OAAO,SAAwB;AAC5C,WAAK,MAAM,QAAQ,EAAE,OAAO,KAAM,CAAA;AAAA,IAAA;AAG/B,SAA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AwB,QAAQ,EAAE,GAAG;AACrC,UAAA,EAAE,OAAW,IAAA;AAEZ,WAAA,QAAQ,CAAC,UAAU;AACxB,UAAI,KAAK,YAAY,IAAI,KAAK,GAAG;AAC/B,aAAK,YAAY,IAAI,KAAK,GAAG,KAAK,OAAO;AAAA,MAAA,OACpC;AACL,aAAK,YAAY,IAAI,OAAO,CAAC,OAAO,CAAC;AACrC,aAAK,eAAe,KAAK;AAAA,MAC3B;AAAA,IAAA,CACD;AAAA,EACH;AAAA,EAEA,OAAO,SAAkB;AACjB,UAAA,uBAAuB,QAAQ,EAAE,GAAG;AAC1C,SAAK,OAAO,OAAO;AACnB,SAAK,IAAI,OAAO;AAAA,EAClB;AAAA,EAEA,OAAO,SAAkB;AACjB,UAAA,0BAA0B,QAAQ,EAAE,GAAG;AAE7C,SAAK,YAAY,QAAQ,CAAC,UAAU,UAAU;AACtC,YAAA,mBAAmB,SAAS,OAAO,CAAC,UAAU,MAAM,OAAO,QAAQ,EAAE;AAGvE,UAAA,iBAAiB,WAAW,GAAG;AAC5B,aAAA,YAAY,OAAO,KAAK;AAC7B,aAAK,eAAe,KAAK;AAAA,MAAA,OACpB;AACA,aAAA,YAAY,IAAI,OAAO,gBAAgB;AAAA,MAC9C;AAAA,IAAA,CACD;AAAA,EACH;AACF;AAKA,SAAwB,oBAAoB,MAA4C;AAC/E,SAAA,IAAI,cAAc,IAAI;AAC/B;"}
1
+ {"version":3,"file":"webhook-runner.mjs","sources":["../../src/services/webhook-runner.ts"],"sourcesContent":["/**\n * The event hub is Strapi's event control center.\n */\n\nimport createdDebugger from 'debug';\nimport _ from 'lodash';\nimport type { Logger } from '@strapi/logger';\n\nimport type { Modules } from '@strapi/types';\nimport WorkerQueue from './worker-queue';\nimport type { EventHub } from './event-hub';\nimport type { Fetch } from '../utils/fetch';\n\ntype Webhook = Modules.WebhookStore.Webhook;\n\ninterface Config {\n defaultHeaders: Record<string, string>;\n}\n\ninterface ConstructorParameters {\n eventHub: EventHub;\n logger: Logger;\n configuration?: Record<string, unknown>;\n fetch: Fetch;\n}\n\ninterface Event {\n event: string;\n info: Record<string, unknown>;\n}\n\ntype Listener = (info: Record<string, unknown>) => Promise<void>;\n\nconst debug = createdDebugger('strapi:webhook');\n\nconst defaultConfiguration: Config = {\n defaultHeaders: {},\n};\n\nclass WebhookRunner {\n private eventHub: EventHub;\n\n private logger: Logger;\n\n private config: Config;\n\n private webhooksMap: Map<string, Webhook[]> = new Map();\n\n private listeners: Map<string, Listener> = new Map();\n\n private queue: WorkerQueue<Event, void>;\n\n private fetch: Fetch;\n\n constructor({ eventHub, logger, configuration = {}, fetch }: ConstructorParameters) {\n debug('Initialized webhook runner');\n this.eventHub = eventHub;\n this.logger = logger;\n this.fetch = fetch;\n\n if (typeof configuration !== 'object') {\n throw new Error(\n 'Invalid configuration provided to the webhookRunner.\\nCheck your server.json -> webhooks configuration'\n );\n }\n\n this.config = _.merge(defaultConfiguration, configuration);\n\n this.queue = new WorkerQueue({ logger, concurrency: 5 });\n\n this.queue.subscribe(this.executeListener.bind(this));\n }\n\n deleteListener(event: string) {\n debug(`Deleting listener for event '${event}'`);\n\n const fn = this.listeners.get(event);\n\n if (fn !== undefined) {\n this.eventHub.off(event, fn);\n this.listeners.delete(event);\n }\n }\n\n createListener(event: string) {\n debug(`Creating listener for event '${event}'`);\n if (this.listeners.has(event)) {\n this.logger.error(\n `The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`\n );\n }\n\n const listen = async (info: Event['info']) => {\n this.queue.enqueue({ event, info });\n };\n\n this.listeners.set(event, listen);\n this.eventHub.on(event, listen);\n }\n\n async executeListener({ event, info }: Event) {\n debug(`Executing webhook for event '${event}'`);\n const webhooks = this.webhooksMap.get(event) || [];\n const activeWebhooks = webhooks.filter((webhook) => webhook.isEnabled === true);\n\n for (const webhook of activeWebhooks) {\n await this.run(webhook, event, info).catch((error: unknown) => {\n this.logger.error('Error running webhook');\n this.logger.error(error);\n });\n }\n }\n\n run(webhook: Webhook, event: string, info = {}) {\n const { url, headers } = webhook;\n\n return this.fetch(url, {\n method: 'post',\n body: JSON.stringify({\n event,\n createdAt: new Date(),\n ...info,\n }),\n headers: {\n ...this.config.defaultHeaders,\n ...headers,\n 'X-Strapi-Event': event,\n 'Content-Type': 'application/json',\n },\n signal: AbortSignal.timeout(10000),\n })\n .then(async (res) => {\n if (res.ok) {\n return {\n statusCode: res.status,\n };\n }\n\n return {\n statusCode: res.status,\n message: await res.text(),\n };\n })\n .catch((err) => {\n return {\n statusCode: 500,\n message: err.message,\n };\n });\n }\n\n add(webhook: Webhook) {\n debug(`Registering webhook '${webhook.id}'`);\n const { events } = webhook;\n\n events.forEach((event) => {\n if (this.webhooksMap.has(event)) {\n this.webhooksMap.get(event)?.push(webhook);\n } else {\n this.webhooksMap.set(event, [webhook]);\n this.createListener(event);\n }\n });\n }\n\n update(webhook: Webhook) {\n debug(`Refreshing webhook '${webhook.id}'`);\n this.remove(webhook);\n this.add(webhook);\n }\n\n remove(webhook: Webhook) {\n debug(`Unregistering webhook '${webhook.id}'`);\n\n this.webhooksMap.forEach((webhooks, event) => {\n const filteredWebhooks = webhooks.filter((value) => value.id !== webhook.id);\n\n // Cleanup hanging listeners\n if (filteredWebhooks.length === 0) {\n this.webhooksMap.delete(event);\n this.deleteListener(event);\n } else {\n this.webhooksMap.set(event, filteredWebhooks);\n }\n });\n }\n}\n\n/**\n * Expose a factory function instead of the class\n */\nexport default function createWebhookRunner(opts: ConstructorParameters): WebhookRunner {\n return new WebhookRunner(opts);\n}\n\nexport type { WebhookRunner };\n"],"names":["createdDebugger"],"mappings":";;;AAiCA,MAAM,QAAQA,eAAgB,gBAAgB;AAE9C,MAAM,uBAA+B;AAAA,EACnC,gBAAgB,CAAC;AACnB;AAEA,MAAM,cAAc;AAAA,EACV;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,kCAA0C;EAE1C,gCAAuC;EAEvC;AAAA,EAEA;AAAA,EAER,YAAY,EAAE,UAAU,QAAQ,gBAA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