From ee6fe89f0a8951cb094d23507ff97d4d5c995da1 Mon Sep 17 00:00:00 2001 From: Iulia Grumaz Date: Wed, 27 Mar 2024 19:48:47 +0200 Subject: [PATCH 1/4] chore: initial draft of spacecat sdk --- .eslintrc.cjs | 8 +- .gitignore | 3 + package-lock.json | 49 ++- .../spacecat-shared-sdk/CODE_OF_CONDUCT.md | 74 ++++ packages/spacecat-shared-sdk/CONTRIBUTING.md | 74 ++++ packages/spacecat-shared-sdk/LICENSE.txt | 264 +++++++++++++ packages/spacecat-shared-sdk/README.md | 1 + .../spacecat-shared-sdk/package-lock.json | 353 ++++++++++++++++++ packages/spacecat-shared-sdk/package.json | 41 ++ packages/spacecat-shared-sdk/src/sdk.js | 301 +++++++++++++++ .../spacecat-shared-sdk/use-cases/README.md | 21 ++ .../use-cases/config-audits-reports.json | 16 + .../use-cases/configure-audits-reports.js | 102 +++++ 13 files changed, 1300 insertions(+), 7 deletions(-) create mode 100644 packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md create mode 100644 packages/spacecat-shared-sdk/CONTRIBUTING.md create mode 100644 packages/spacecat-shared-sdk/LICENSE.txt create mode 100644 packages/spacecat-shared-sdk/README.md create mode 100644 packages/spacecat-shared-sdk/package-lock.json create mode 100644 packages/spacecat-shared-sdk/package.json create mode 100644 packages/spacecat-shared-sdk/src/sdk.js create mode 100644 packages/spacecat-shared-sdk/use-cases/README.md create mode 100644 packages/spacecat-shared-sdk/use-cases/config-audits-reports.json create mode 100644 packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js diff --git a/.eslintrc.cjs b/.eslintrc.cjs index cdc3af60..c3f7c1dc 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -35,10 +35,10 @@ module.exports = { rules: {}, }, { - files: ["*.test.js"], + files: ['*.test.js'], rules: { - "no-unused-expressions": "off" - } - } + 'no-unused-expressions': 'off', + }, + }, ], }; diff --git a/.gitignore b/.gitignore index 664eaead..abc1d4d0 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,6 @@ junit # Files deliberately excluded from version control *DO-NOT-COMMIT* + +# macOS +.DS_Store diff --git a/package-lock.json b/package-lock.json index 4b188053..8e268860 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3711,6 +3711,11 @@ "dev": true, "license": "MIT" }, + "node_modules/base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, "node_modules/before-after-hook": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-3.0.2.tgz", @@ -12174,6 +12179,10 @@ "node": ">=0.10.0" } }, + "node_modules/spacecat-sdk": { + "resolved": "packages/spacecat-shared-sdk", + "link": true + }, "node_modules/spawn-error-forwarder": { "version": "1.0.0", "dev": true, @@ -13149,7 +13158,7 @@ }, "packages/spacecat-shared-data-access": { "name": "@adobe/spacecat-shared-data-access", - "version": "1.20.5", + "version": "1.21.0", "license": "Apache-2.0", "dependencies": { "@adobe/spacecat-shared-dynamo": "1.2.5", @@ -13720,7 +13729,7 @@ }, "packages/spacecat-shared-ims-client": { "name": "@adobe/spacecat-shared-ims-client", - "version": "1.2.2", + "version": "1.3.0", "license": "Apache-2.0", "dependencies": { "@adobe/fetch": "4.1.1", @@ -13768,9 +13777,25 @@ "version": "1.4.0", "license": "Apache-2.0" }, + "packages/spacecat-shared-sdk": { + "version": "1.0.0-pre-initial-version.0", + "license": "Apache-2.0", + "dependencies": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0" + }, + "devDependencies": { + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } + }, "packages/spacecat-shared-slack-client": { "name": "@adobe/spacecat-shared-slack-client", - "version": "1.2.1", + "version": "1.3.0", "license": "Apache-2.0", "dependencies": { "@adobe/helix-universal": "4.5.0", @@ -17025,6 +17050,11 @@ "version": "1.0.2", "dev": true }, + "base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, "before-after-hook": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-3.0.2.tgz", @@ -22467,6 +22497,19 @@ "version": "0.6.1", "dev": true }, + "spacecat-sdk": { + "version": "file:packages/spacecat-shared-sdk", + "requires": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0", + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } + }, "spawn-error-forwarder": { "version": "1.0.0", "dev": true diff --git a/packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md b/packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..75f92707 --- /dev/null +++ b/packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Adobe Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at Grp-opensourceoffice@adobe.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ \ No newline at end of file diff --git a/packages/spacecat-shared-sdk/CONTRIBUTING.md b/packages/spacecat-shared-sdk/CONTRIBUTING.md new file mode 100644 index 00000000..01bbeac1 --- /dev/null +++ b/packages/spacecat-shared-sdk/CONTRIBUTING.md @@ -0,0 +1,74 @@ +# Contributing to Project Franklin + +This project (like almost all of Project Franklin) is an Open Development project and welcomes contributions from everyone who finds it useful or lacking. + +## Code Of Conduct + +This project adheres to the Adobe [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to cstaub at adobe dot com. + +## Contributor License Agreement + +All third-party contributions to this project must be accompanied by a signed contributor license. This gives Adobe permission to redistribute your contributions as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html)! You only need to submit an Adobe CLA one time, so if you have submitted one previously, you are good to go! + +## Things to Keep in Mind + +This project uses a **commit then review** process, which means that for approved maintainers, changes can be merged immediately, but will be reviewed by others. + +For other contributors, a maintainer of the project has to approve the pull request. + +# Before You Contribute + +* Check that there is an existing issue in GitHub issues +* Check if there are other pull requests that might overlap or conflict with your intended contribution + +# How to Contribute + +1. Fork the repository +2. Make some changes on a branch on your fork +3. Create a pull request from your branch + +In your pull request, outline: + +* What the changes intend +* How they change the existing code +* If (and what) they breaks +* Start the pull request with the GitHub issue ID, e.g. #123 + +Lastly, please follow the [pull request template](.github/pull_request_template.md) when submitting a pull request! + +Each commit message that is not part of a pull request: + +* Should contain the issue ID like `#123` +* Can contain the tag `[trivial]` for trivial changes that don't relate to an issue + + + +## Coding Styleguides + +We enforce a coding styleguide using `eslint`. As part of your build, run `npm run lint` to check if your code is conforming to the style guide. We do the same for every PR in our CI, so PRs will get rejected if they don't follow the style guide. + +You can fix some of the issues automatically by running `npx eslint . --fix`. + +## Commit Message Format + +This project uses a structured commit changelog format that should be used for every commit. Use `npm run commit` instead of your usual `git commit` to generate commit messages using a wizard. + +```bash +# either add all changed files +$ git add -A +# or selectively add files +$ git add package.json +# then commit using the wizard +$ npm run commit +``` + +# How Contributions get Reviewed + +One of the maintainers will look at the pull request within one week. Feedback on the pull request will be given in writing, in GitHub. + +# Release Management + +The project's committers will release to the [Adobe organization on npmjs.org](https://www.npmjs.com/org/adobe). +Please contact the [Adobe Open Source Advisory Board](https://git.corp.adobe.com/OpenSourceAdvisoryBoard/discuss/issues) to get access to the npmjs organization. + +The release process is fully automated using `semantic-release`, increasing the version numbers, etc. based on the contents of the commit messages found. diff --git a/packages/spacecat-shared-sdk/LICENSE.txt b/packages/spacecat-shared-sdk/LICENSE.txt new file mode 100644 index 00000000..883ab098 --- /dev/null +++ b/packages/spacecat-shared-sdk/LICENSE.txt @@ -0,0 +1,264 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +APACHE JACKRABBIT SUBCOMPONENTS + +Apache Jackrabbit includes parts with separate copyright notices and license +terms. Your use of these subcomponents is subject to the terms and conditions +of the following licenses: + + XPath 2.0/XQuery 1.0 Parser: + http://www.w3.org/2002/11/xquery-xpath-applets/xgrammar.zip + + Copyright (C) 2002 World Wide Web Consortium, (Massachusetts Institute of + Technology, European Research Consortium for Informatics and Mathematics, + Keio University). All Rights Reserved. + + This work is distributed under the W3C(R) Software License in the hope + that it will be useful, but WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + W3C(R) SOFTWARE NOTICE AND LICENSE + http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 + + This work (and included software, documentation such as READMEs, or + other related items) is being provided by the copyright holders under + the following license. By obtaining, using and/or copying this work, + you (the licensee) agree that you have read, understood, and will comply + with the following terms and conditions. + + Permission to copy, modify, and distribute this software and its + documentation, with or without modification, for any purpose and + without fee or royalty is hereby granted, provided that you include + the following on ALL copies of the software and documentation or + portions thereof, including modifications: + + 1. The full text of this NOTICE in a location viewable to users + of the redistributed or derivative work. + + 2. Any pre-existing intellectual property disclaimers, notices, + or terms and conditions. If none exist, the W3C Software Short + Notice should be included (hypertext is preferred, text is + permitted) within the body of any redistributed or derivative code. + + 3. Notice of any changes or modifications to the files, including + the date changes were made. (We recommend you provide URIs to the + location from which the code is derived.) + + THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT + HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS + FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR + DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, + TRADEMARKS OR OTHER RIGHTS. + + COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL + OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR + DOCUMENTATION. + + The name and trademarks of copyright holders may NOT be used in + advertising or publicity pertaining to the software without specific, + written prior permission. Title to copyright in this software and + any associated documentation will at all times remain with + copyright holders. diff --git a/packages/spacecat-shared-sdk/README.md b/packages/spacecat-shared-sdk/README.md new file mode 100644 index 00000000..fd52c8db --- /dev/null +++ b/packages/spacecat-shared-sdk/README.md @@ -0,0 +1 @@ +# SpaceCat SDK diff --git a/packages/spacecat-shared-sdk/package-lock.json b/packages/spacecat-shared-sdk/package-lock.json new file mode 100644 index 00000000..a89d377b --- /dev/null +++ b/packages/spacecat-shared-sdk/package-lock.json @@ -0,0 +1,353 @@ +{ + "name": "spacecat-sdk", + "version": "1.0.0-pre-initial-version.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "spacecat-sdk", + "version": "1.0.0-pre-initial-version.0", + "license": "Apache-2.0", + "dependencies": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0" + }, + "devDependencies": { + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } + }, + "node_modules/@adobe/fetch": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@adobe/fetch/-/fetch-4.1.1.tgz", + "integrity": "sha512-EechqpvFBFs1Fq8/E3hNxxyv2HU9xDKFV5tyUTESNQwaMn9kKHidqu2pv0WAJuuBvxRVdVc3gRhUEePFLwXfmw==", + "dependencies": { + "debug": "4.3.4", + "http-cache-semantics": "4.1.1", + "lru-cache": "7.18.3" + }, + "engines": { + "node": ">=14.16" + } + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", + "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", + "dev": true, + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz", + "integrity": "sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@sinonjs/samsam": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-8.0.0.tgz", + "integrity": "sha512-Bp8KUVlLp8ibJZrnvq2foVhP0IVX2CIprMJPK0vqGqgrDa0OHVKeZyBykqskkrdxV6yKBPmGasO8LVjAKR3Gew==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^2.0.0", + "lodash.get": "^4.4.2", + "type-detect": "^4.0.8" + } + }, + "node_modules/@sinonjs/samsam/node_modules/@sinonjs/commons": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-2.0.0.tgz", + "integrity": "sha512-uLa0j859mMrg2slwQYdO/AkrOfmH+X6LTVmNTS9CqexuE2IvVORIkSpJLqePAbEnKJ77aMmCwr1NUZ57120Xcg==", + "dev": true, + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/text-encoding": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz", + "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==", + "dev": true + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, + "node_modules/chai": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", + "integrity": "sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==", + "dev": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.0.8" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chai-as-promised": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/chai-as-promised/-/chai-as-promised-7.1.1.tgz", + "integrity": "sha512-azL6xMoi+uxu6z4rhWQ1jbdUhOMhis2PvscD/xjLqNMkv3BPPp2JyyuTHOrf9BOosGpNQ11v6BKv/g57RXbiaA==", + "dev": true, + "dependencies": { + "check-error": "^1.0.2" + }, + "peerDependencies": { + "chai": ">= 2.1.2 < 5" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/diff": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz", + "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", + "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" + }, + "node_modules/husky": { + "version": "9.0.11", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.0.11.tgz", + "integrity": "sha512-AB6lFlbwwyIqMdHYhwPe+kjOC3Oc5P3nThEoW/AaO2BX3vJDjWPFxYLxokUZOo6RNX20He3AaT8sESs9NJcmEw==", + "dev": true, + "bin": { + "husky": "bin.mjs" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "dev": true + }, + "node_modules/just-extend": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz", + "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==", + "dev": true + }, + "node_modules/lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", + "dev": true + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/nise": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.9.tgz", + "integrity": "sha512-qOnoujW4SV6e40dYxJOb3uvuoPHtmLzIk4TFo+j0jPJoC+5Z9xja5qH5JZobEPsa8+YYphMrOSwnrshEhG2qww==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0", + "@sinonjs/fake-timers": "^11.2.2", + "@sinonjs/text-encoding": "^0.7.2", + "just-extend": "^6.2.0", + "path-to-regexp": "^6.2.1" + } + }, + "node_modules/nock": { + "version": "13.5.4", + "resolved": "https://registry.npmjs.org/nock/-/nock-13.5.4.tgz", + "integrity": "sha512-yAyTfdeNJGGBFxWdzSKCBYxs5FxLbCg5X5Q4ets974hcQzG1+qCxvIyOo4j2Ry6MUlhWVMX4OoYDefAIIwupjw==", + "dev": true, + "dependencies": { + "debug": "^4.1.0", + "json-stringify-safe": "^5.0.1", + "propagate": "^2.0.0" + }, + "engines": { + "node": ">= 10.13" + } + }, + "node_modules/path-to-regexp": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.1.tgz", + "integrity": "sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==", + "dev": true + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/propagate": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/propagate/-/propagate-2.0.1.tgz", + "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/sinon": { + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/sinon/-/sinon-17.0.1.tgz", + "integrity": "sha512-wmwE19Lie0MLT+ZYNpDymasPHUKTaZHUH/pKEubRXIzySv9Atnlw+BUMGCzWgV7b7wO+Hw6f1TEOr0IUnmU8/g==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0", + "@sinonjs/fake-timers": "^11.2.2", + "@sinonjs/samsam": "^8.0.0", + "diff": "^5.1.0", + "nise": "^5.1.5", + "supports-color": "^7.2.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/sinon" + } + }, + "node_modules/sinon-chai": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/sinon-chai/-/sinon-chai-3.7.0.tgz", + "integrity": "sha512-mf5NURdUaSdnatJx3uhoBOrY9dtL19fiOtAdT1Azxg3+lNJFiuN0uzaU3xX1LeAfL17kHQhTAJgpsfhbMJMY2g==", + "dev": true, + "peerDependencies": { + "chai": "^4.0.0", + "sinon": ">=4.0.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "engines": { + "node": ">=4" + } + } + } +} diff --git a/packages/spacecat-shared-sdk/package.json b/packages/spacecat-shared-sdk/package.json new file mode 100644 index 00000000..849361a2 --- /dev/null +++ b/packages/spacecat-shared-sdk/package.json @@ -0,0 +1,41 @@ +{ + "name": "spacecat-sdk", + "version": "1.0.0-pre-initial-version.0", + "description": "SpaceCat SDK for Node.js", + "type": "module", + "main": "src/index.js", + "scripts": { + "lint": "eslint src --fix", + "clean": "rm -rf package-lock.json node_modules", + "test": "echo \"Error: no tests\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/adobe/spacecat-sdk.git" + }, + "author": "Adobe Inc.", + "license": "Apache-2.0", + "keywords": [ + "aem", + "sdk" + ], + "bugs": { + "url": "https://github.com/adobe/spacecat-sdk/issues" + }, + "homepage": "https://github.com/adobe/spacecat-sdk#readme", + "publishConfig": { + "access": "public" + }, + "dependencies": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0" + }, + "devDependencies": { + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } +} diff --git a/packages/spacecat-shared-sdk/src/sdk.js b/packages/spacecat-shared-sdk/src/sdk.js new file mode 100644 index 00000000..6b3dc0a7 --- /dev/null +++ b/packages/spacecat-shared-sdk/src/sdk.js @@ -0,0 +1,301 @@ +/* + * Copyright 2024 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +import { fetch } from '@adobe/fetch'; +import pkg from 'base-64'; + +const { encode } = pkg; + +export default class SpaceCatSdk { + constructor(config, log = console) { + this.config = config; + this.config.headers = { + 'Content-Type': 'application/json', + ...config.headers, + 'x-api-key': config.apiKey, + }; + this.log = log; + } + + async callApi({ + url = '/', method = 'GET', headers = this.config.headers, body = {}, nullFor404 = false, + }) { + try { + this.log.info(`Calling API with URL: ${url}, method: ${method}, body: ${JSON.stringify(body)}`); + + const response = await fetch(url, { + method, + headers, + ...(method === 'GET' ? {} : { body: JSON.stringify(body) }), + }); + + if (!response.ok) { + if (nullFor404 && response.status === 404) { + this.log.warn(`Resource not found: ${url}`); + return null; + } + throw new Error(`Request failed with status code ${response.status}`); + } + + const responseData = await response.json(); + this.log.info(`API call successful. Response: ${JSON.stringify(responseData)}`); + + return responseData; + } catch (error) { + this.log.error(`Error in API call. URL: ${url}, method: ${method}, body: ${JSON.stringify(body)}. Error: ${error.message}`); + throw error; + } + } + + async getOrganization(imsOrgId, { nullFor404 = false } = {}) { + try { + const url = `${this.config.apiBaseUrl}/organizations/by-ims-org-id/${imsOrgId}`; + return this.callApi({ url, nullFor404 }); + } catch (error) { + this.log.error(`Error in getOrganization function. Error: ${error.message}`); + throw error; + } + } + + async getOrganizationById(orgId, { nullFor404 = false } = {}) { + try { + const url = `${this.config.apiBaseUrl}/organizations/${orgId}`; + return this.callApi({ url, nullFor404 }); + } catch (error) { + this.log.error(`Error in getOrganizationById function. Error: ${error.message}`); + throw error; + } + } + + async createOrganization({ imsOrgId, orgName }) { + try { + const url = `${this.config.apiBaseUrl}/organizations`; + const body = { + name: orgName, + imsOrgId, + }; + + return this.callApi({ url, method: 'POST', body }); + } catch (error) { + this.log.error(`Error in createOrganization function. Error: ${error.message}`); + throw error; + } + } + + async getSite(siteBaseUrl, { nullFor404 = false } = {}) { + try { + const base64EncodedUrl = encode(siteBaseUrl); + const url = `${this.config.apiBaseUrl}/sites/by-base-url/${base64EncodedUrl}`; + + return this.callApi({ url, nullFor404 }); + } catch (error) { + this.log.error(`Error in getSite function. Error: ${error.message}`); + throw error; + } + } + + async createSite({ orgId, siteBaseUrl }) { + try { + const url = `${this.config.apiBaseUrl}/sites`; + const body = { + organizationId: orgId, + baseURL: siteBaseUrl, + }; + + return this.callApi({ url, method: 'POST', body }); + } catch (error) { + this.log.error(`Error in createSite function. Error: ${error.message}`); + throw error; + } + } + + async createOrRetrieveOrganization({ imsOrgId, orgName }) { + try { + let organization = await this.getOrganization(imsOrgId, { nullFor404: true }); + if (organization) { + return organization; + } + organization = await this.createOrganization({ imsOrgId, orgName }); + return organization; + } catch (error) { + this.log.error(`Error in createOrRetrieveOrganization function. Error: ${error.message}`); + throw error; + } + } + + async createOrRetrieveSite({ orgId, siteBaseUrl }) { + try { + let site = await this.getSite(siteBaseUrl, { nullFor404: true }); + if (site) { + return site; + } + site = await this.createSite({ orgId, siteBaseUrl }); + return site; + } catch (error) { + this.log.error(`Error in createOrRetrieveSite function. Error: ${error.message}`); + throw error; + } + } + + static updateAuditsConfig({ auditConfig = {}, auditTypes = [], enable = true }) { + const updatedAuditConfig = { ...auditConfig }; + // updatedAuditConfig.auditsDisabled = !enable; + updatedAuditConfig.auditTypeConfigs = updatedAuditConfig?.auditTypeConfigs || {}; + + auditTypes.forEach((auditType) => { + updatedAuditConfig.auditTypeConfigs[auditType] = { disabled: !enable }; + }); + + return updatedAuditConfig; + } + + async configureAuditsForOrganization({ organization, auditTypes = [], enable = true }) { + try { + const updatedConfig = { ...organization.config }; + updatedConfig.audits = SpaceCatSdk.updateAuditsConfig( + { auditConfig: organization?.config?.audits, auditTypes, enable }, + ); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/organizations/${organization.id}`, + method: 'PATCH', + body: { config: updatedConfig }, + }); + + this.log.info(`Audit types '${auditTypes.join(', ')}' ${enable ? 'enabled' : 'disabled'} successfully at organization level for organization ${organization.id}`); + + return responseData; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } + + async configureAuditsForSite({ site, auditTypes = [], enable = true }) { + try { + const updatedAuditConfig = SpaceCatSdk.updateAuditsConfig( + { auditConfig: site?.auditConfig, auditTypes, enable }, + ); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/sites/${site.id}`, + method: 'PATCH', + body: { auditConfig: updatedAuditConfig }, + }); + + this.log.info(`Audit types '${auditTypes.join(', ')}' ${enable ? 'enabled' : 'disabled'} successfully at site level for site ${site.id}`); + + return responseData; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } + + static updateReportsConfig({ + config, auditTypes = [], byOrg, channelId, userIds, isOrgLevel = true, + }) { + const updatedConfig = { ...config }; + updatedConfig.alerts = updatedConfig?.alerts || []; + if (channelId) { + updatedConfig.slack = { channel: channelId }; + } + + auditTypes.forEach((auditType) => { + const existingAlertIndex = updatedConfig.alerts + .findIndex((alert) => alert.type === auditType); + + let alertConfig; + if (existingAlertIndex === -1) { + alertConfig = { + type: auditType, + }; + if (userIds) { + alertConfig.mentions = [{ slack: userIds.map((userId) => (`<@${userId}>`)) }]; + } + if (isOrgLevel) { + alertConfig.byOrg = byOrg; + } + console.log(`New alert config: ${JSON.stringify(alertConfig)}`); + updatedConfig.alerts.push(alertConfig); + } else { + alertConfig = updatedConfig.alerts[existingAlertIndex]; + if (userIds) { + alertConfig.mentions = [{ slack: userIds.map((userId) => (`<@${userId}>`)) }]; + } + if (isOrgLevel) { + alertConfig.byOrg = byOrg; + } + console.log(`Existing updated alert config: ${JSON.stringify(alertConfig)}`); + } + }); + + return updatedConfig; + } + + async enableReportsAtOrganizationLevel({ + organization, auditTypes, channelId, userIds, byOrg = true, + }) { + try { + const updatedConfig = SpaceCatSdk.updateReportsConfig({ + config: organization?.config, auditTypes, byOrg, channelId, userIds, isOrgLevel: true, + }); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/organizations/${organization.id}`, + method: 'PATCH', + body: { + config: updatedConfig, + }, + }); + + this.log.info(`Reporting for audit types '${auditTypes.join(', ')}' configured byOrg ${byOrg} successfully at organization level for organization ${organization.id}`); + + return { + id: responseData?.id, + config: responseData?.config, + slack: responseData?.slack, + }; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } + + async enableReportsAtSiteLevel({ + site, auditTypes, channelId, userIds, byOrg, + }) { + try { + const updatedConfig = SpaceCatSdk.updateReportsConfig({ + config: site?.config, auditTypes, byOrg, channelId, userIds, isOrgLevel: false, + }); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/sites/${site.id}`, + method: 'PATCH', + body: { + config: updatedConfig, + }, + }); + + this.log.info(`Reporting for audit types '${auditTypes.join(', ')}' configured byOrg ${byOrg} successfully at site level for site ${site.id}`); + + return { + id: responseData?.id, + config: responseData?.config, + slack: responseData?.slack, + }; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } +} diff --git a/packages/spacecat-shared-sdk/use-cases/README.md b/packages/spacecat-shared-sdk/use-cases/README.md new file mode 100644 index 00000000..1e5b5820 --- /dev/null +++ b/packages/spacecat-shared-sdk/use-cases/README.md @@ -0,0 +1,21 @@ +# SpaceCat SDK + +## Use Case: Configure Audits and Reports +Enabling or disabling audits and configure reporting (i.e. alerts) for a list of sites within a single specified +organization. +If the sites are already created, assumption is that they have the correct organizationId set. +If configuration already exists (slack channel, mentions, byOrg, disabled for that audit type), the script will +overwrite the existing values. + +### Configuration +See `config-audits-reports.json` for an example configuration file. +Fill in the `config-audits-reports.json` file with the following information: +- mandatory: `imsOrgId` and `orgName`, if the organization is new, or `orgId` if the organization already exists in + SpaceCat. The script doesn't work without an organization. +- mandatory: `siteBaseUrls` with one or more **base URLs** (without `www`, with `https://`, without trailing `/`) of + the sites to configure. + +### Usage +```bash +node configure-audits-reports.js config-audits-reports.json +``` diff --git a/packages/spacecat-shared-sdk/use-cases/config-audits-reports.json b/packages/spacecat-shared-sdk/use-cases/config-audits-reports.json new file mode 100644 index 00000000..5d6f1135 --- /dev/null +++ b/packages/spacecat-shared-sdk/use-cases/config-audits-reports.json @@ -0,0 +1,16 @@ +{ + "imsOrgId": "IMSORGID@AdobeOrg", + "orgName": "Organization name as it appears in IMS", + "orgId": "organizationId--from-SpaceCat", + "siteBaseUrls": ["https://example.com"], + "channelId": "C-slack-channel-id", + "userIds": ["U-slack-user-id"], + "auditTypes": ["404", "broken-backlinks"], + "configureAudits": true, + "enableAudits": true, + "auditsByOrg": false, + "configureReports": true, + "reportsByOrg": false, + "apiBaseUrl": "https://spacecat.experiencecloud.live/api/v1", + "apiKey": "admin-api-key" +} diff --git a/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js new file mode 100644 index 00000000..7238b178 --- /dev/null +++ b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js @@ -0,0 +1,102 @@ +/* + * Copyright 2024 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +import { promises as fs } from 'fs'; + +import SpaceCatSdk from '../src/sdk.js'; + +const log = console; + +async function readConfig(configFilePath) { + try { + const jsonString = await fs.readFile(configFilePath, 'utf8'); + const config = JSON.parse(jsonString); + log.info('Config is:', config); + return config; + } catch (err) { + if (err.code === 'ENOENT') { + log.error('Config file read failed:', err); + throw new Error('Config file read failed'); + } else { + log.error('Error parsing config JSON string:', err); + throw new Error('Error parsing config JSON string'); + } + } +} + +(async () => { + // Assuming that the file path is the first command line argument + const configFilePath = process.argv[2]; + const config = await readConfig(configFilePath); + const { + imsOrgId, + orgName, + siteBaseUrls, + auditTypes, + channelId, + userIds, + configureAudits, + enableAudits, + auditsByOrg, + configureReports, + reportsByOrg, + apiBaseUrl, + apiKey, + orgId, + } = config; + + const sdk = new SpaceCatSdk({ apiBaseUrl, apiKey }); + + let organization; + if (orgId) { + organization = await sdk.getOrganizationById(orgId, { nullFor404: true }); + } else { + organization = await sdk.createOrRetrieveOrganization({ imsOrgId, orgName }); + } + if (!organization) { + log.error('Failed to create or retrieve organization'); + return; + } + + if (configureAudits && auditsByOrg) { + await sdk.configureAuditsForOrganization({ organization, auditTypes, enable: enableAudits }); + } + + if (configureReports) { + if (reportsByOrg) { + await sdk.enableReportsAtOrganizationLevel({ + organization, auditTypes, byOrg: true, channelId, userIds, + }); + } else { + await sdk.enableReportsAtOrganizationLevel({ organization, auditTypes, byOrg: false }); + } + } + + await Promise.all(siteBaseUrls.map(async (siteBaseUrl) => { + const site = await sdk.createOrRetrieveSite({ orgId: organization.id, siteBaseUrl }); + if (!site) { + log.error('Failed to create or retrieve site'); + return; + } + + if (configureAudits) { + await sdk.configureAuditsForSite({ site, auditTypes, enable: enableAudits }); + } + + if (configureReports) { + if (!reportsByOrg) { + await sdk.enableReportsAtSiteLevel({ + site, auditTypes, channelId, userIds, byOrg: false, + }); + } + } + })); +})(); From 5c4cca0192721786b3c362d47c23e8cb3512de90 Mon Sep 17 00:00:00 2001 From: Iulia Grumaz Date: Wed, 27 Mar 2024 20:04:53 +0200 Subject: [PATCH 2/4] chore: initial draft of spacecat sdk --- .../spacecat-shared-sdk/use-cases/configure-audits-reports.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js index 7238b178..5c3b8992 100644 --- a/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js +++ b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js @@ -99,4 +99,5 @@ async function readConfig(configFilePath) { } } })); + process.exit(0); })(); From 6499001385ed8b8ff1dc792f91cdb9012a153056 Mon Sep 17 00:00:00 2001 From: Iulia Grumaz Date: Wed, 27 Mar 2024 19:48:47 +0200 Subject: [PATCH 3/4] chore: initial draft of spacecat sdk --- .eslintrc.cjs | 8 +- .gitignore | 3 + package-lock.json | 49 ++- .../spacecat-shared-sdk/CODE_OF_CONDUCT.md | 74 ++++ packages/spacecat-shared-sdk/CONTRIBUTING.md | 74 ++++ packages/spacecat-shared-sdk/LICENSE.txt | 264 +++++++++++++ packages/spacecat-shared-sdk/README.md | 1 + .../spacecat-shared-sdk/package-lock.json | 353 ++++++++++++++++++ packages/spacecat-shared-sdk/package.json | 41 ++ packages/spacecat-shared-sdk/src/sdk.js | 301 +++++++++++++++ .../spacecat-shared-sdk/use-cases/README.md | 21 ++ .../use-cases/config-audits-reports.json | 16 + .../use-cases/configure-audits-reports.js | 102 +++++ 13 files changed, 1300 insertions(+), 7 deletions(-) create mode 100644 packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md create mode 100644 packages/spacecat-shared-sdk/CONTRIBUTING.md create mode 100644 packages/spacecat-shared-sdk/LICENSE.txt create mode 100644 packages/spacecat-shared-sdk/README.md create mode 100644 packages/spacecat-shared-sdk/package-lock.json create mode 100644 packages/spacecat-shared-sdk/package.json create mode 100644 packages/spacecat-shared-sdk/src/sdk.js create mode 100644 packages/spacecat-shared-sdk/use-cases/README.md create mode 100644 packages/spacecat-shared-sdk/use-cases/config-audits-reports.json create mode 100644 packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js diff --git a/.eslintrc.cjs b/.eslintrc.cjs index cdc3af60..c3f7c1dc 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -35,10 +35,10 @@ module.exports = { rules: {}, }, { - files: ["*.test.js"], + files: ['*.test.js'], rules: { - "no-unused-expressions": "off" - } - } + 'no-unused-expressions': 'off', + }, + }, ], }; diff --git a/.gitignore b/.gitignore index 664eaead..abc1d4d0 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,6 @@ junit # Files deliberately excluded from version control *DO-NOT-COMMIT* + +# macOS +.DS_Store diff --git a/package-lock.json b/package-lock.json index 4b188053..8e268860 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3711,6 +3711,11 @@ "dev": true, "license": "MIT" }, + "node_modules/base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, "node_modules/before-after-hook": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-3.0.2.tgz", @@ -12174,6 +12179,10 @@ "node": ">=0.10.0" } }, + "node_modules/spacecat-sdk": { + "resolved": "packages/spacecat-shared-sdk", + "link": true + }, "node_modules/spawn-error-forwarder": { "version": "1.0.0", "dev": true, @@ -13149,7 +13158,7 @@ }, "packages/spacecat-shared-data-access": { "name": "@adobe/spacecat-shared-data-access", - "version": "1.20.5", + "version": "1.21.0", "license": "Apache-2.0", "dependencies": { "@adobe/spacecat-shared-dynamo": "1.2.5", @@ -13720,7 +13729,7 @@ }, "packages/spacecat-shared-ims-client": { "name": "@adobe/spacecat-shared-ims-client", - "version": "1.2.2", + "version": "1.3.0", "license": "Apache-2.0", "dependencies": { "@adobe/fetch": "4.1.1", @@ -13768,9 +13777,25 @@ "version": "1.4.0", "license": "Apache-2.0" }, + "packages/spacecat-shared-sdk": { + "version": "1.0.0-pre-initial-version.0", + "license": "Apache-2.0", + "dependencies": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0" + }, + "devDependencies": { + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } + }, "packages/spacecat-shared-slack-client": { "name": "@adobe/spacecat-shared-slack-client", - "version": "1.2.1", + "version": "1.3.0", "license": "Apache-2.0", "dependencies": { "@adobe/helix-universal": "4.5.0", @@ -17025,6 +17050,11 @@ "version": "1.0.2", "dev": true }, + "base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, "before-after-hook": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-3.0.2.tgz", @@ -22467,6 +22497,19 @@ "version": "0.6.1", "dev": true }, + "spacecat-sdk": { + "version": "file:packages/spacecat-shared-sdk", + "requires": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0", + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } + }, "spawn-error-forwarder": { "version": "1.0.0", "dev": true diff --git a/packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md b/packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..75f92707 --- /dev/null +++ b/packages/spacecat-shared-sdk/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Adobe Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at Grp-opensourceoffice@adobe.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ \ No newline at end of file diff --git a/packages/spacecat-shared-sdk/CONTRIBUTING.md b/packages/spacecat-shared-sdk/CONTRIBUTING.md new file mode 100644 index 00000000..01bbeac1 --- /dev/null +++ b/packages/spacecat-shared-sdk/CONTRIBUTING.md @@ -0,0 +1,74 @@ +# Contributing to Project Franklin + +This project (like almost all of Project Franklin) is an Open Development project and welcomes contributions from everyone who finds it useful or lacking. + +## Code Of Conduct + +This project adheres to the Adobe [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to cstaub at adobe dot com. + +## Contributor License Agreement + +All third-party contributions to this project must be accompanied by a signed contributor license. This gives Adobe permission to redistribute your contributions as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html)! You only need to submit an Adobe CLA one time, so if you have submitted one previously, you are good to go! + +## Things to Keep in Mind + +This project uses a **commit then review** process, which means that for approved maintainers, changes can be merged immediately, but will be reviewed by others. + +For other contributors, a maintainer of the project has to approve the pull request. + +# Before You Contribute + +* Check that there is an existing issue in GitHub issues +* Check if there are other pull requests that might overlap or conflict with your intended contribution + +# How to Contribute + +1. Fork the repository +2. Make some changes on a branch on your fork +3. Create a pull request from your branch + +In your pull request, outline: + +* What the changes intend +* How they change the existing code +* If (and what) they breaks +* Start the pull request with the GitHub issue ID, e.g. #123 + +Lastly, please follow the [pull request template](.github/pull_request_template.md) when submitting a pull request! + +Each commit message that is not part of a pull request: + +* Should contain the issue ID like `#123` +* Can contain the tag `[trivial]` for trivial changes that don't relate to an issue + + + +## Coding Styleguides + +We enforce a coding styleguide using `eslint`. As part of your build, run `npm run lint` to check if your code is conforming to the style guide. We do the same for every PR in our CI, so PRs will get rejected if they don't follow the style guide. + +You can fix some of the issues automatically by running `npx eslint . --fix`. + +## Commit Message Format + +This project uses a structured commit changelog format that should be used for every commit. Use `npm run commit` instead of your usual `git commit` to generate commit messages using a wizard. + +```bash +# either add all changed files +$ git add -A +# or selectively add files +$ git add package.json +# then commit using the wizard +$ npm run commit +``` + +# How Contributions get Reviewed + +One of the maintainers will look at the pull request within one week. Feedback on the pull request will be given in writing, in GitHub. + +# Release Management + +The project's committers will release to the [Adobe organization on npmjs.org](https://www.npmjs.com/org/adobe). +Please contact the [Adobe Open Source Advisory Board](https://git.corp.adobe.com/OpenSourceAdvisoryBoard/discuss/issues) to get access to the npmjs organization. + +The release process is fully automated using `semantic-release`, increasing the version numbers, etc. based on the contents of the commit messages found. diff --git a/packages/spacecat-shared-sdk/LICENSE.txt b/packages/spacecat-shared-sdk/LICENSE.txt new file mode 100644 index 00000000..883ab098 --- /dev/null +++ b/packages/spacecat-shared-sdk/LICENSE.txt @@ -0,0 +1,264 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +APACHE JACKRABBIT SUBCOMPONENTS + +Apache Jackrabbit includes parts with separate copyright notices and license +terms. Your use of these subcomponents is subject to the terms and conditions +of the following licenses: + + XPath 2.0/XQuery 1.0 Parser: + http://www.w3.org/2002/11/xquery-xpath-applets/xgrammar.zip + + Copyright (C) 2002 World Wide Web Consortium, (Massachusetts Institute of + Technology, European Research Consortium for Informatics and Mathematics, + Keio University). All Rights Reserved. + + This work is distributed under the W3C(R) Software License in the hope + that it will be useful, but WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + W3C(R) SOFTWARE NOTICE AND LICENSE + http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 + + This work (and included software, documentation such as READMEs, or + other related items) is being provided by the copyright holders under + the following license. By obtaining, using and/or copying this work, + you (the licensee) agree that you have read, understood, and will comply + with the following terms and conditions. + + Permission to copy, modify, and distribute this software and its + documentation, with or without modification, for any purpose and + without fee or royalty is hereby granted, provided that you include + the following on ALL copies of the software and documentation or + portions thereof, including modifications: + + 1. The full text of this NOTICE in a location viewable to users + of the redistributed or derivative work. + + 2. Any pre-existing intellectual property disclaimers, notices, + or terms and conditions. If none exist, the W3C Software Short + Notice should be included (hypertext is preferred, text is + permitted) within the body of any redistributed or derivative code. + + 3. Notice of any changes or modifications to the files, including + the date changes were made. (We recommend you provide URIs to the + location from which the code is derived.) + + THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT + HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS + FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR + DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, + TRADEMARKS OR OTHER RIGHTS. + + COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL + OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR + DOCUMENTATION. + + The name and trademarks of copyright holders may NOT be used in + advertising or publicity pertaining to the software without specific, + written prior permission. Title to copyright in this software and + any associated documentation will at all times remain with + copyright holders. diff --git a/packages/spacecat-shared-sdk/README.md b/packages/spacecat-shared-sdk/README.md new file mode 100644 index 00000000..fd52c8db --- /dev/null +++ b/packages/spacecat-shared-sdk/README.md @@ -0,0 +1 @@ +# SpaceCat SDK diff --git a/packages/spacecat-shared-sdk/package-lock.json b/packages/spacecat-shared-sdk/package-lock.json new file mode 100644 index 00000000..a89d377b --- /dev/null +++ b/packages/spacecat-shared-sdk/package-lock.json @@ -0,0 +1,353 @@ +{ + "name": "spacecat-sdk", + "version": "1.0.0-pre-initial-version.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "spacecat-sdk", + "version": "1.0.0-pre-initial-version.0", + "license": "Apache-2.0", + "dependencies": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0" + }, + "devDependencies": { + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } + }, + "node_modules/@adobe/fetch": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@adobe/fetch/-/fetch-4.1.1.tgz", + "integrity": "sha512-EechqpvFBFs1Fq8/E3hNxxyv2HU9xDKFV5tyUTESNQwaMn9kKHidqu2pv0WAJuuBvxRVdVc3gRhUEePFLwXfmw==", + "dependencies": { + "debug": "4.3.4", + "http-cache-semantics": "4.1.1", + "lru-cache": "7.18.3" + }, + "engines": { + "node": ">=14.16" + } + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", + "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", + "dev": true, + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz", + "integrity": "sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@sinonjs/samsam": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-8.0.0.tgz", + "integrity": "sha512-Bp8KUVlLp8ibJZrnvq2foVhP0IVX2CIprMJPK0vqGqgrDa0OHVKeZyBykqskkrdxV6yKBPmGasO8LVjAKR3Gew==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^2.0.0", + "lodash.get": "^4.4.2", + "type-detect": "^4.0.8" + } + }, + "node_modules/@sinonjs/samsam/node_modules/@sinonjs/commons": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-2.0.0.tgz", + "integrity": "sha512-uLa0j859mMrg2slwQYdO/AkrOfmH+X6LTVmNTS9CqexuE2IvVORIkSpJLqePAbEnKJ77aMmCwr1NUZ57120Xcg==", + "dev": true, + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/text-encoding": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz", + "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==", + "dev": true + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, + "node_modules/chai": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", + "integrity": "sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==", + "dev": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.0.8" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chai-as-promised": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/chai-as-promised/-/chai-as-promised-7.1.1.tgz", + "integrity": "sha512-azL6xMoi+uxu6z4rhWQ1jbdUhOMhis2PvscD/xjLqNMkv3BPPp2JyyuTHOrf9BOosGpNQ11v6BKv/g57RXbiaA==", + "dev": true, + "dependencies": { + "check-error": "^1.0.2" + }, + "peerDependencies": { + "chai": ">= 2.1.2 < 5" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/diff": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz", + "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", + "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" + }, + "node_modules/husky": { + "version": "9.0.11", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.0.11.tgz", + "integrity": "sha512-AB6lFlbwwyIqMdHYhwPe+kjOC3Oc5P3nThEoW/AaO2BX3vJDjWPFxYLxokUZOo6RNX20He3AaT8sESs9NJcmEw==", + "dev": true, + "bin": { + "husky": "bin.mjs" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "dev": true + }, + "node_modules/just-extend": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz", + "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==", + "dev": true + }, + "node_modules/lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", + "dev": true + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/nise": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.9.tgz", + "integrity": "sha512-qOnoujW4SV6e40dYxJOb3uvuoPHtmLzIk4TFo+j0jPJoC+5Z9xja5qH5JZobEPsa8+YYphMrOSwnrshEhG2qww==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0", + "@sinonjs/fake-timers": "^11.2.2", + "@sinonjs/text-encoding": "^0.7.2", + "just-extend": "^6.2.0", + "path-to-regexp": "^6.2.1" + } + }, + "node_modules/nock": { + "version": "13.5.4", + "resolved": "https://registry.npmjs.org/nock/-/nock-13.5.4.tgz", + "integrity": "sha512-yAyTfdeNJGGBFxWdzSKCBYxs5FxLbCg5X5Q4ets974hcQzG1+qCxvIyOo4j2Ry6MUlhWVMX4OoYDefAIIwupjw==", + "dev": true, + "dependencies": { + "debug": "^4.1.0", + "json-stringify-safe": "^5.0.1", + "propagate": "^2.0.0" + }, + "engines": { + "node": ">= 10.13" + } + }, + "node_modules/path-to-regexp": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.1.tgz", + "integrity": "sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==", + "dev": true + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/propagate": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/propagate/-/propagate-2.0.1.tgz", + "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/sinon": { + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/sinon/-/sinon-17.0.1.tgz", + "integrity": "sha512-wmwE19Lie0MLT+ZYNpDymasPHUKTaZHUH/pKEubRXIzySv9Atnlw+BUMGCzWgV7b7wO+Hw6f1TEOr0IUnmU8/g==", + "dev": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0", + "@sinonjs/fake-timers": "^11.2.2", + "@sinonjs/samsam": "^8.0.0", + "diff": "^5.1.0", + "nise": "^5.1.5", + "supports-color": "^7.2.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/sinon" + } + }, + "node_modules/sinon-chai": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/sinon-chai/-/sinon-chai-3.7.0.tgz", + "integrity": "sha512-mf5NURdUaSdnatJx3uhoBOrY9dtL19fiOtAdT1Azxg3+lNJFiuN0uzaU3xX1LeAfL17kHQhTAJgpsfhbMJMY2g==", + "dev": true, + "peerDependencies": { + "chai": "^4.0.0", + "sinon": ">=4.0.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "engines": { + "node": ">=4" + } + } + } +} diff --git a/packages/spacecat-shared-sdk/package.json b/packages/spacecat-shared-sdk/package.json new file mode 100644 index 00000000..849361a2 --- /dev/null +++ b/packages/spacecat-shared-sdk/package.json @@ -0,0 +1,41 @@ +{ + "name": "spacecat-sdk", + "version": "1.0.0-pre-initial-version.0", + "description": "SpaceCat SDK for Node.js", + "type": "module", + "main": "src/index.js", + "scripts": { + "lint": "eslint src --fix", + "clean": "rm -rf package-lock.json node_modules", + "test": "echo \"Error: no tests\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/adobe/spacecat-sdk.git" + }, + "author": "Adobe Inc.", + "license": "Apache-2.0", + "keywords": [ + "aem", + "sdk" + ], + "bugs": { + "url": "https://github.com/adobe/spacecat-sdk/issues" + }, + "homepage": "https://github.com/adobe/spacecat-sdk#readme", + "publishConfig": { + "access": "public" + }, + "dependencies": { + "@adobe/fetch": "4.1.1", + "base-64": "1.0.0" + }, + "devDependencies": { + "chai": "4.4.1", + "chai-as-promised": "7.1.1", + "husky": "9.0.11", + "nock": "13.5.4", + "sinon": "17.0.1", + "sinon-chai": "3.7.0" + } +} diff --git a/packages/spacecat-shared-sdk/src/sdk.js b/packages/spacecat-shared-sdk/src/sdk.js new file mode 100644 index 00000000..6b3dc0a7 --- /dev/null +++ b/packages/spacecat-shared-sdk/src/sdk.js @@ -0,0 +1,301 @@ +/* + * Copyright 2024 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +import { fetch } from '@adobe/fetch'; +import pkg from 'base-64'; + +const { encode } = pkg; + +export default class SpaceCatSdk { + constructor(config, log = console) { + this.config = config; + this.config.headers = { + 'Content-Type': 'application/json', + ...config.headers, + 'x-api-key': config.apiKey, + }; + this.log = log; + } + + async callApi({ + url = '/', method = 'GET', headers = this.config.headers, body = {}, nullFor404 = false, + }) { + try { + this.log.info(`Calling API with URL: ${url}, method: ${method}, body: ${JSON.stringify(body)}`); + + const response = await fetch(url, { + method, + headers, + ...(method === 'GET' ? {} : { body: JSON.stringify(body) }), + }); + + if (!response.ok) { + if (nullFor404 && response.status === 404) { + this.log.warn(`Resource not found: ${url}`); + return null; + } + throw new Error(`Request failed with status code ${response.status}`); + } + + const responseData = await response.json(); + this.log.info(`API call successful. Response: ${JSON.stringify(responseData)}`); + + return responseData; + } catch (error) { + this.log.error(`Error in API call. URL: ${url}, method: ${method}, body: ${JSON.stringify(body)}. Error: ${error.message}`); + throw error; + } + } + + async getOrganization(imsOrgId, { nullFor404 = false } = {}) { + try { + const url = `${this.config.apiBaseUrl}/organizations/by-ims-org-id/${imsOrgId}`; + return this.callApi({ url, nullFor404 }); + } catch (error) { + this.log.error(`Error in getOrganization function. Error: ${error.message}`); + throw error; + } + } + + async getOrganizationById(orgId, { nullFor404 = false } = {}) { + try { + const url = `${this.config.apiBaseUrl}/organizations/${orgId}`; + return this.callApi({ url, nullFor404 }); + } catch (error) { + this.log.error(`Error in getOrganizationById function. Error: ${error.message}`); + throw error; + } + } + + async createOrganization({ imsOrgId, orgName }) { + try { + const url = `${this.config.apiBaseUrl}/organizations`; + const body = { + name: orgName, + imsOrgId, + }; + + return this.callApi({ url, method: 'POST', body }); + } catch (error) { + this.log.error(`Error in createOrganization function. Error: ${error.message}`); + throw error; + } + } + + async getSite(siteBaseUrl, { nullFor404 = false } = {}) { + try { + const base64EncodedUrl = encode(siteBaseUrl); + const url = `${this.config.apiBaseUrl}/sites/by-base-url/${base64EncodedUrl}`; + + return this.callApi({ url, nullFor404 }); + } catch (error) { + this.log.error(`Error in getSite function. Error: ${error.message}`); + throw error; + } + } + + async createSite({ orgId, siteBaseUrl }) { + try { + const url = `${this.config.apiBaseUrl}/sites`; + const body = { + organizationId: orgId, + baseURL: siteBaseUrl, + }; + + return this.callApi({ url, method: 'POST', body }); + } catch (error) { + this.log.error(`Error in createSite function. Error: ${error.message}`); + throw error; + } + } + + async createOrRetrieveOrganization({ imsOrgId, orgName }) { + try { + let organization = await this.getOrganization(imsOrgId, { nullFor404: true }); + if (organization) { + return organization; + } + organization = await this.createOrganization({ imsOrgId, orgName }); + return organization; + } catch (error) { + this.log.error(`Error in createOrRetrieveOrganization function. Error: ${error.message}`); + throw error; + } + } + + async createOrRetrieveSite({ orgId, siteBaseUrl }) { + try { + let site = await this.getSite(siteBaseUrl, { nullFor404: true }); + if (site) { + return site; + } + site = await this.createSite({ orgId, siteBaseUrl }); + return site; + } catch (error) { + this.log.error(`Error in createOrRetrieveSite function. Error: ${error.message}`); + throw error; + } + } + + static updateAuditsConfig({ auditConfig = {}, auditTypes = [], enable = true }) { + const updatedAuditConfig = { ...auditConfig }; + // updatedAuditConfig.auditsDisabled = !enable; + updatedAuditConfig.auditTypeConfigs = updatedAuditConfig?.auditTypeConfigs || {}; + + auditTypes.forEach((auditType) => { + updatedAuditConfig.auditTypeConfigs[auditType] = { disabled: !enable }; + }); + + return updatedAuditConfig; + } + + async configureAuditsForOrganization({ organization, auditTypes = [], enable = true }) { + try { + const updatedConfig = { ...organization.config }; + updatedConfig.audits = SpaceCatSdk.updateAuditsConfig( + { auditConfig: organization?.config?.audits, auditTypes, enable }, + ); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/organizations/${organization.id}`, + method: 'PATCH', + body: { config: updatedConfig }, + }); + + this.log.info(`Audit types '${auditTypes.join(', ')}' ${enable ? 'enabled' : 'disabled'} successfully at organization level for organization ${organization.id}`); + + return responseData; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } + + async configureAuditsForSite({ site, auditTypes = [], enable = true }) { + try { + const updatedAuditConfig = SpaceCatSdk.updateAuditsConfig( + { auditConfig: site?.auditConfig, auditTypes, enable }, + ); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/sites/${site.id}`, + method: 'PATCH', + body: { auditConfig: updatedAuditConfig }, + }); + + this.log.info(`Audit types '${auditTypes.join(', ')}' ${enable ? 'enabled' : 'disabled'} successfully at site level for site ${site.id}`); + + return responseData; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } + + static updateReportsConfig({ + config, auditTypes = [], byOrg, channelId, userIds, isOrgLevel = true, + }) { + const updatedConfig = { ...config }; + updatedConfig.alerts = updatedConfig?.alerts || []; + if (channelId) { + updatedConfig.slack = { channel: channelId }; + } + + auditTypes.forEach((auditType) => { + const existingAlertIndex = updatedConfig.alerts + .findIndex((alert) => alert.type === auditType); + + let alertConfig; + if (existingAlertIndex === -1) { + alertConfig = { + type: auditType, + }; + if (userIds) { + alertConfig.mentions = [{ slack: userIds.map((userId) => (`<@${userId}>`)) }]; + } + if (isOrgLevel) { + alertConfig.byOrg = byOrg; + } + console.log(`New alert config: ${JSON.stringify(alertConfig)}`); + updatedConfig.alerts.push(alertConfig); + } else { + alertConfig = updatedConfig.alerts[existingAlertIndex]; + if (userIds) { + alertConfig.mentions = [{ slack: userIds.map((userId) => (`<@${userId}>`)) }]; + } + if (isOrgLevel) { + alertConfig.byOrg = byOrg; + } + console.log(`Existing updated alert config: ${JSON.stringify(alertConfig)}`); + } + }); + + return updatedConfig; + } + + async enableReportsAtOrganizationLevel({ + organization, auditTypes, channelId, userIds, byOrg = true, + }) { + try { + const updatedConfig = SpaceCatSdk.updateReportsConfig({ + config: organization?.config, auditTypes, byOrg, channelId, userIds, isOrgLevel: true, + }); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/organizations/${organization.id}`, + method: 'PATCH', + body: { + config: updatedConfig, + }, + }); + + this.log.info(`Reporting for audit types '${auditTypes.join(', ')}' configured byOrg ${byOrg} successfully at organization level for organization ${organization.id}`); + + return { + id: responseData?.id, + config: responseData?.config, + slack: responseData?.slack, + }; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } + + async enableReportsAtSiteLevel({ + site, auditTypes, channelId, userIds, byOrg, + }) { + try { + const updatedConfig = SpaceCatSdk.updateReportsConfig({ + config: site?.config, auditTypes, byOrg, channelId, userIds, isOrgLevel: false, + }); + + const responseData = await this.callApi({ + url: `${this.config.apiBaseUrl}/sites/${site.id}`, + method: 'PATCH', + body: { + config: updatedConfig, + }, + }); + + this.log.info(`Reporting for audit types '${auditTypes.join(', ')}' configured byOrg ${byOrg} successfully at site level for site ${site.id}`); + + return { + id: responseData?.id, + config: responseData?.config, + slack: responseData?.slack, + }; + } catch (error) { + this.log.error('Error:', error.message); + return null; + } + } +} diff --git a/packages/spacecat-shared-sdk/use-cases/README.md b/packages/spacecat-shared-sdk/use-cases/README.md new file mode 100644 index 00000000..1e5b5820 --- /dev/null +++ b/packages/spacecat-shared-sdk/use-cases/README.md @@ -0,0 +1,21 @@ +# SpaceCat SDK + +## Use Case: Configure Audits and Reports +Enabling or disabling audits and configure reporting (i.e. alerts) for a list of sites within a single specified +organization. +If the sites are already created, assumption is that they have the correct organizationId set. +If configuration already exists (slack channel, mentions, byOrg, disabled for that audit type), the script will +overwrite the existing values. + +### Configuration +See `config-audits-reports.json` for an example configuration file. +Fill in the `config-audits-reports.json` file with the following information: +- mandatory: `imsOrgId` and `orgName`, if the organization is new, or `orgId` if the organization already exists in + SpaceCat. The script doesn't work without an organization. +- mandatory: `siteBaseUrls` with one or more **base URLs** (without `www`, with `https://`, without trailing `/`) of + the sites to configure. + +### Usage +```bash +node configure-audits-reports.js config-audits-reports.json +``` diff --git a/packages/spacecat-shared-sdk/use-cases/config-audits-reports.json b/packages/spacecat-shared-sdk/use-cases/config-audits-reports.json new file mode 100644 index 00000000..5d6f1135 --- /dev/null +++ b/packages/spacecat-shared-sdk/use-cases/config-audits-reports.json @@ -0,0 +1,16 @@ +{ + "imsOrgId": "IMSORGID@AdobeOrg", + "orgName": "Organization name as it appears in IMS", + "orgId": "organizationId--from-SpaceCat", + "siteBaseUrls": ["https://example.com"], + "channelId": "C-slack-channel-id", + "userIds": ["U-slack-user-id"], + "auditTypes": ["404", "broken-backlinks"], + "configureAudits": true, + "enableAudits": true, + "auditsByOrg": false, + "configureReports": true, + "reportsByOrg": false, + "apiBaseUrl": "https://spacecat.experiencecloud.live/api/v1", + "apiKey": "admin-api-key" +} diff --git a/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js new file mode 100644 index 00000000..7238b178 --- /dev/null +++ b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js @@ -0,0 +1,102 @@ +/* + * Copyright 2024 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +import { promises as fs } from 'fs'; + +import SpaceCatSdk from '../src/sdk.js'; + +const log = console; + +async function readConfig(configFilePath) { + try { + const jsonString = await fs.readFile(configFilePath, 'utf8'); + const config = JSON.parse(jsonString); + log.info('Config is:', config); + return config; + } catch (err) { + if (err.code === 'ENOENT') { + log.error('Config file read failed:', err); + throw new Error('Config file read failed'); + } else { + log.error('Error parsing config JSON string:', err); + throw new Error('Error parsing config JSON string'); + } + } +} + +(async () => { + // Assuming that the file path is the first command line argument + const configFilePath = process.argv[2]; + const config = await readConfig(configFilePath); + const { + imsOrgId, + orgName, + siteBaseUrls, + auditTypes, + channelId, + userIds, + configureAudits, + enableAudits, + auditsByOrg, + configureReports, + reportsByOrg, + apiBaseUrl, + apiKey, + orgId, + } = config; + + const sdk = new SpaceCatSdk({ apiBaseUrl, apiKey }); + + let organization; + if (orgId) { + organization = await sdk.getOrganizationById(orgId, { nullFor404: true }); + } else { + organization = await sdk.createOrRetrieveOrganization({ imsOrgId, orgName }); + } + if (!organization) { + log.error('Failed to create or retrieve organization'); + return; + } + + if (configureAudits && auditsByOrg) { + await sdk.configureAuditsForOrganization({ organization, auditTypes, enable: enableAudits }); + } + + if (configureReports) { + if (reportsByOrg) { + await sdk.enableReportsAtOrganizationLevel({ + organization, auditTypes, byOrg: true, channelId, userIds, + }); + } else { + await sdk.enableReportsAtOrganizationLevel({ organization, auditTypes, byOrg: false }); + } + } + + await Promise.all(siteBaseUrls.map(async (siteBaseUrl) => { + const site = await sdk.createOrRetrieveSite({ orgId: organization.id, siteBaseUrl }); + if (!site) { + log.error('Failed to create or retrieve site'); + return; + } + + if (configureAudits) { + await sdk.configureAuditsForSite({ site, auditTypes, enable: enableAudits }); + } + + if (configureReports) { + if (!reportsByOrg) { + await sdk.enableReportsAtSiteLevel({ + site, auditTypes, channelId, userIds, byOrg: false, + }); + } + } + })); +})(); From fc400341d48a07e16b2920ead417b0c76f9e1e32 Mon Sep 17 00:00:00 2001 From: Iulia Grumaz Date: Wed, 27 Mar 2024 20:04:53 +0200 Subject: [PATCH 4/4] chore: initial draft of spacecat sdk --- .../spacecat-shared-sdk/use-cases/configure-audits-reports.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js index 7238b178..5c3b8992 100644 --- a/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js +++ b/packages/spacecat-shared-sdk/use-cases/configure-audits-reports.js @@ -99,4 +99,5 @@ async function readConfig(configFilePath) { } } })); + process.exit(0); })();