Skip to content

Commit

Permalink
✨ js-storefrontaware-utils
Browse files Browse the repository at this point in the history
  • Loading branch information
Plopix committed Jun 3, 2022
1 parent 4bb8a3f commit 6e080a2
Show file tree
Hide file tree
Showing 21 changed files with 512 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Thanks for your pull request! We love contributions.

However, this repository is what we call a "subtree split": a read-only copy of one directory of the main repository. It enables developers to depend on specific repository.

If you want to contribute, you should instead open a pull request on the main repository:

https://github.com/CrystallizeAPI/libraries

Thank you for your contribution!

PS: if you haven't already, please add tests.
9 changes: 9 additions & 0 deletions components/js-storefrontaware-utils/.github/issue_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Thanks for reporting an issue! We love feedback.

However, this repository is what we call a "subtree split": a read-only copy of one directory of the main repository. It enables developers to depend on specific repository.

If you want to report or contribute, you should instead open your issue on the main repository:

https://github.com/CrystallizeAPI/libraries

Thank you for your contribution!
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
on:
issues:
types: [opened, edited]

jobs:
autoclose:
runs-on: ubuntu-latest
steps:
- name: Close Issue
uses: peter-evans/close-issue@v1
with:
comment: |
Thanks for reporting an issue! We love feedback.
However, this repository is what we call a "subtree split": a read-only copy of one directory of the main repository. It enables developers to depend on specific repository.
If you want to report or contribute, you should instead open your issue on the main repository:
https://github.com/CrystallizeAPI/libraries
Thank you for your contribution!
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
on:
pull_request:
types: [opened, edited, reopened]

jobs:
autoclose:
runs-on: ubuntu-latest
steps:
- name: Close Pull Request
uses: peter-evans/close-pull@v1
with:
comment: |
Thanks for your pull request! We love contributions.
However, this repository is what we call a "subtree split": a read-only copy of one directory of the main repository. It enables developers to depend on specific repository.
If you want to contribute, you should instead open a pull request on the main repository:
https://github.com/CrystallizeAPI/libraries
Thank you for your contribution!
PS: if you haven't already, please add tests.
44 changes: 44 additions & 0 deletions components/js-storefrontaware-utils/.github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
on:
push:
tags:
- '*'

name: Release a New Version

jobs:
releaseandpublish:
name: Release on Github and Publish on NPM
runs-on: ubuntu-latest
steps:
- name: ⬇️ Checkout repo
uses: actions/checkout@v3

- name: ⎔ Setup node
uses: actions/setup-node@v3
with:
node-version: 16
always-auth: true
registry-url: 'https://registry.npmjs.org'
scope: '@crystallize'

- name: 📥 Download deps
run: yarn install

- name: 🏄 Run the tests
run: yarn build && yarn test

- name: 🏷 Create Release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false

- name: 📢 Publish to NPM
run: yarn publish --new-version ${GITHUB_REF#"refs/tags/"} --no-git-tag-version
env:
NPM_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
5 changes: 5 additions & 0 deletions components/js-storefrontaware-utils/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
dist/

yarn.lock
package-lock.json
Empty file.
21 changes: 21 additions & 0 deletions components/js-storefrontaware-utils/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2022 Crystallize, https://crystallize.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
11 changes: 11 additions & 0 deletions components/js-storefrontaware-utils/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Crystallize JS StoreFront Aware

---

This repository is what we call a "subtree split": a read-only copy of one directory of the main repository.

If you want to report or contribute, you should do it on the main repository: https://github.com/CrystallizeAPI/libraries

---

Utils for MultiSiteFactory
34 changes: 34 additions & 0 deletions components/js-storefrontaware-utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "@crystallize/js-storefrontaware-utils",
"license": "MIT",
"version": "0.1.0",
"author": "Crystallize <hello@crystallize.com> (https://crystallize.com)",
"contributors": [
"Sébastien Morel <sebastien@crystallize.com>"
],
"scripts": {
"watch": "yarn tsc -W",
"build": "yarn tsc",
"test": "jest",
"bump": "yarn tsc && yarn version --no-git-tag-version --new-version"
},
"repository": {
"type": "git",
"url": "https://github.com/CrystallizeAPI/js-storefrontaware-utils.git"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"devDependencies": {
"@tsconfig/node16": "^1.0.2",
"@types/node": "^17.0.23",
"jest": "^27.5.1"
},
"dependencies": {
"typescript": "^4.6.3",
"@crystallize/js-api-client": "*"
},
"peerDependencies": {
"react": "*",
"react-dom": "*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { TStoreFrontAdapter, TStoreFrontConfig } from '../types';
import fs from 'fs/promises';

export const createFilesystemAdapter = (filename: string): TStoreFrontAdapter => {
return {
config: async (withSecrets: boolean): Promise<TStoreFrontConfig> => {
const data = await fs.readFile(filename, { encoding: 'utf8' });
return JSON.parse(data);
},
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { TStoreFrontAdapter, TStoreFrontConfig } from '../types';

export const createMemoryAdapter = (config: TStoreFrontConfig): TStoreFrontAdapter => {
return {
config: async (withSecrets: boolean): Promise<TStoreFrontConfig> => config,
};
};
187 changes: 187 additions & 0 deletions components/js-storefrontaware-utils/src/adapters/superfast.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import { ClientConfiguration, createClient } from '@crystallize/js-api-client';
import crypto from 'crypto';
import { TStoreFrontAdapter, TStoreFrontConfig } from '../types';

type TStorage = {
get: (key: string) => Promise<any>;
set: (key: string, value: any, ttl: number) => Promise<void>;
};

export const createSuperFastAdapter = (
hostname: string,
credentials: ClientConfiguration,
storageClient: TStorage,
ttl: number,
): TStoreFrontAdapter => {
const memoryCache: Record<
string,
{
expiresAt: number;
value: any;
}
> = {};

return {
config: async (withSecrets: boolean): Promise<TStoreFrontConfig> => {
const domainkey = hostname.split('.')[0];
if (memoryCache[domainkey]) {
if (memoryCache[domainkey].expiresAt > Date.now() / 1000) {
return memoryCache[domainkey].value;
}
}

const hit = await storageClient.get(domainkey);
let config: TStoreFrontConfig | undefined = undefined;

if (!hit) {
config = await fetchSuperFastConfig(domainkey, credentials);
memoryCache[domainkey] = {
expiresAt: Math.floor(Date.now() / 1000) + ttl,
value: config,
};
await storageClient.set(domainkey, JSON.stringify(config), ttl);
} else {
config = await JSON.parse(hit);
memoryCache[domainkey] = {
expiresAt: Math.floor(Date.now() / 1000) + ttl,
value: config,
};
}

if (config !== undefined) {
if (withSecrets) {
config.configuration = cypher(`${process.env.ENCRYPTED_PARAMS_SECRET}`).decryptMap(
config.configuration,
);
}
return config;
}
throw new Error('Impossible to fetch SuperFast config');
},
};
};

async function fetchSuperFastConfig(domainkey: string, credentials: ClientConfiguration): Promise<TStoreFrontConfig> {
const query = `query {
catalogue(path:"/tenants/${domainkey}") {
name
components{
id
content {
__typename
...on SingleLineContent{
text
}
...on RichTextContent {
html
}
...on SelectionContent {
options {
key
value
}
}
...on BooleanContent {
value
}
...on ImageContent {
firstImage{
url
}
}
...on PropertiesTableContent {
sections {
title
properties {
key
value
}
}
}
}
}
}
}`;

const client = createClient(credentials);
const tenant = await client.catalogueApi(query);
const components = tenant.catalogue.components.reduce((result: any, component: any) => {
function toString(component: any): string | boolean {
switch (component?.content?.__typename) {
case 'SingleLineContent':
return component.content.text;
case 'RichTextContent':
return component.content.html.join('');
case 'SelectionContent':
return component.content.options[0].key;
case 'BooleanContent':
return component.content.value;
case 'ImageContent':
return component.content.firstImage.url;
case 'PropertiesTableContent':
return component.content.sections.reduce((result: any, section: any) => {
section.properties.forEach((property: any) => {
result[property.key] = property.value;
});
return result;
}, {});
default:
return false;
}
}
return {
...result,
[component.id]: toString(component),
};
}, {});
return {
identifier: domainkey,
tenantIdentifier: components['tenant-identifier'],
language: 'en',
storefront: components['storefront'],
logo: components['logos'],
theme: components['theme'],
configuration: components['configuration'],
};
}

const cypher = (
secret: string,
): {
encrypt: (text: string) => string;
decrypt: (text: string) => string;
decryptMap: (map: { [key: string]: string }) => { [key: string]: string };
} => {
const key = crypto.createHash('sha256').update(String(secret)).digest('base64').substring(0, 32);
const algorithm = 'aes-256-cbc';
function encrypt(value: string): string {
const initVector = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, initVector);
let encryptedData = cipher.update(value, 'utf-8', 'hex');
encryptedData += cipher.final('hex');
return `${initVector.toString('hex')}:${encryptedData}`;
}

function decrypt(value: string): string {
const [initVector, encryptedData] = value.split(':');
const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(initVector, 'hex'));
let decryptedData = decipher.update(encryptedData, 'hex', 'utf-8');
decryptedData += decipher.final('utf8');
return decryptedData;
}

return {
encrypt,
decrypt,
decryptMap: (map: { [key: string]: string }) => {
let result = {};
Object.keys(map).forEach((key: string) => {
result = {
...result,
[key]: decrypt(map[key]),
};
});
return result;
},
};
};
Loading

0 comments on commit 6e080a2

Please sign in to comment.