Skip to content

Commit

Permalink
new pwa-studio update
Browse files Browse the repository at this point in the history
  • Loading branch information
Cody Nguyen committed Mar 13, 2021
1 parent 6226d8e commit e5c92ea
Show file tree
Hide file tree
Showing 13 changed files with 127 additions and 15,198 deletions.
7 changes: 5 additions & 2 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@
# Uncomment and modify variable declarations in this file and they will take
# effect throughout the Buildpack tool chain.
#
# Generated by @magento/pwa-buildpack v7.0.0 on 2021-02-04T09:48:15.890Z.
# Generated by @magento/pwa-buildpack v8.0.1 on 2021-03-13T09:42:44.759Z.
#
################################################################################

#### Connecting to a Magento store #############################################
#
# Connect to an instance of Magento 2.3 by specifying its public domain name.
#MAGENTO_BACKEND_URL=https://master-7rqtwti-mfwmkrjfqvbjk.us-4.magentosite.cloud/
MAGENTO_BACKEND_URL=https://mp.pwa-commerce.com/
#
################################################################################
Expand All @@ -37,6 +36,10 @@ MAGENTO_BACKEND_EDITION=CE
# - Default when not set:
STORE_VIEW_CODE=
#
# Includes the store code in the store URLs if value is true.
# - Default when not set: false
USE_STORE_CODE_IN_URL=false
#
################################################################################

#### Image Optimizing Origin ###################################################
Expand Down
8 changes: 5 additions & 3 deletions .graphqlconfig
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"projects": {
"demo": {
"simi-studio": {
"schemaPath": "lastCachedGraphQLSchema.json",
"extensions": {
"endpoints": {
Expand All @@ -11,9 +11,11 @@
"apollo",
"literal"
],
"filesGlob": "../{venia-ui,venia-concept}/{lib,src}/**/*.{js,graphql,gql}",
"filesGlob": "../{peregrine,venia-ui,venia-concept}/{lib,src}/**/*.{js,graphql,gql}",
"ignore": [
"../venia-ui/lib/**/giftOptions.js"
"../venia-ui/lib/**/giftOptions.js",
"../venia-ui/lib/**/wishlistPage.gql.js",
"../venia-ui/lib/**/wishlistItem.gql.js"
]
}
}
Expand Down
15 changes: 15 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.idea
.vscode
coverage
node_modules
storybook-dist
test-results
dist
.DS_Store
.env
build-stats.json
npm-debug.log
lastCachedGraphQLSchema.json
test-report.xml
test-results.json
yarn-error.log
2 changes: 1 addition & 1 deletion local-intercept.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@
* or modify functionality from its dependencies.
*/

function localIntercept(targets) {}
function localIntercept() {}

module.exports = localIntercept;
24 changes: 13 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "demo",
"name": "simi-studio",
"private": true,
"version": "2.0.0",
"version": "3.0.0",
"description": "A new project based on @magento/venia-concept",
"author": "SimiCart",
"license": "UNLICENSED",
Expand All @@ -12,14 +12,14 @@
"build:dev": "yarn run clean && yarn run validate-queries && webpack --no-progress --env.mode development",
"build:prod": "yarn run clean && webpack --no-progress --env.mode production",
"clean": "rimraf dist",
"download-schema": "graphql get-schema --project demo --insecure",
"download-schema": "graphql get-schema --project simi-studio --insecure",
"lint": "eslint --ignore-path .gitignore 'src/**/{*.js,package.json}'",
"prettier": "prettier --loglevel warn --ignore-path .gitignore 'src/**/*.@(css|graphql|js)' '*.js'",
"prettier:check": "yarn run -s prettier -- --check",
"prettier:fix": "yarn run -s prettier -- --write",
"start": "buildpack serve .",
"start:debug": "node --inspect-brk ./node_modules/.bin/webpack-dev-server --progress --color --env.mode development",
"validate-queries": "yarn run download-schema && graphql validate-magento-pwa-queries --project demo",
"validate-queries": "yarn run download-schema && graphql validate-magento-pwa-queries --project simi-studio",
"watch": "webpack-dev-server --progress --color --env.mode development",
"storybook": "start-storybook -p 9001 -c src/.storybook",
"storybook:build": "build-storybook -c src/.storybook -o storybook-dist"
Expand All @@ -29,8 +29,8 @@
"@magento/venia-drivers": "src/drivers"
},
"dependencies": {
"@magento/pwa-buildpack": "~7.0.0",
"reactjs-popup": "^2.0.4"
"@magento/pwa-buildpack": "~8.0.1",
"sharp": "~0.23.3"
},
"devDependencies": {
"@adobe/apollo-link-mutation-queue": "~1.0.2",
Expand All @@ -46,10 +46,11 @@
"@babel/runtime": "~7.4.2",
"@magento/babel-preset-peregrine": "~1.1.0",
"@magento/eslint-config": "~1.5.0",
"@magento/pagebuilder": "~3.0.0",
"@magento/peregrine": "~8.0.0",
"@magento/upward-security-headers": "~1.0.0",
"@magento/venia-ui": "~5.0.0",
"@magento/pagebuilder": "~4.0.1",
"@magento/peregrine": "~9.0.0",
"@magento/upward-security-headers": "~1.0.2",
"@magento/venia-adobe-data-layer": "~0.0.1",
"@magento/venia-ui": "~6.0.1",
"@pmmmwh/react-refresh-webpack-plugin": "0.4.1",
"@storybook/react": "~5.2.6",
"apollo-cache-persist": "~0.1.1",
Expand All @@ -71,7 +72,7 @@
"eslint-plugin-jsx-a11y": "~6.2.1",
"eslint-plugin-node": "~8.0.1",
"eslint-plugin-package-json": "~0.1.3",
"eslint-plugin-react": "~7.12.4",
"eslint-plugin-react": "~7.21.5",
"eslint-plugin-react-hooks": "~2.0.1",
"express": "~4.16.4",
"file-loader": "~4.0.0",
Expand All @@ -82,6 +83,7 @@
"informed": "~2.11.17",
"jarallax": "~1.11.1",
"load-google-maps-api": "~2.0.1",
"lodash": "~4.17.20",
"lodash.escape": "~4.0.1",
"lodash.get": "~4.4.2",
"lodash.over": "~4.7.0",
Expand Down
15 changes: 12 additions & 3 deletions src/.storybook/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const path = require('path');
const {
graphQL: { getPossibleTypes, getStoreConfigData },
graphQL: {
getPossibleTypes,
getStoreConfigData,
getAvailableStoresConfigData
},
Utilities: { loadEnvironment }
} = require('@magento/pwa-buildpack');
const baseWebpackConfig = require('../../webpack.config');
Expand All @@ -11,7 +15,7 @@ const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'
// defines in the docs.
// See https://storybook.js.org/docs/configurations/custom-webpack-config/#full-control-mode
module.exports = async ({ config: storybookBaseConfig, mode }) => {
const projectConfig = loadEnvironment(
const projectConfig = await loadEnvironment(
// Load .env from root
path.resolve(__dirname, '../..')
);
Expand All @@ -22,6 +26,7 @@ module.exports = async ({ config: storybookBaseConfig, mode }) => {

const possibleTypes = await getPossibleTypes();
const storeConfigData = await getStoreConfigData();
const { availableStores } = await getAvailableStoresConfigData();
global.LOCALE = storeConfigData.locale.replace('_', '-');

const webpackConfig = await baseWebpackConfig(mode);
Expand All @@ -33,12 +38,16 @@ module.exports = async ({ config: storybookBaseConfig, mode }) => {
storybookBaseConfig.plugins = [
...storybookBaseConfig.plugins,
new DefinePlugin({
__fetchLocaleData__: async () => {
// no-op in storybook
},
POSSIBLE_TYPES: JSON.stringify(possibleTypes),
STORE_NAME: JSON.stringify('Storybook'),
STORE_VIEW_LOCALE: JSON.stringify(global.LOCALE),
STORE_VIEW_CODE: process.env.STORE_VIEW_CODE
? JSON.stringify(process.env.STORE_VIEW_CODE)
: JSON.stringify(storeConfigData.code)
: JSON.stringify(storeConfigData.code),
AVAILABLE_STORE_VIEWS: JSON.stringify(availableStores)
}),
new EnvironmentPlugin(projectConfig.env),
new ReactRefreshWebpackPlugin()
Expand Down
26 changes: 14 additions & 12 deletions src/ServiceWorker/Utilities/imageCacheHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,29 @@ import { ExpirationPlugin } from 'workbox-expiration';
import { PREFETCH_IMAGES } from '@magento/venia-ui/lib/constants/swMessageTypes';

import { isFastNetwork } from './networkUtils';
import { THIRTY_DAYS, CATALOG_CACHE_NAME } from '../defaults';
import { THIRTY_DAYS, IMAGES_CACHE_NAME } from '../defaults';
import { registerMessageHandler } from './messageHandler';

const imageRegex = new RegExp(/\.(?:png|jpg|jpeg)$/);

const getWidth = url => Number(new URLSearchParams(url.search).get('width'));

const isCatalogImage = ({ url }) => url.pathname.startsWith('/media/catalog');
const isImage = url => imageRegex.test(url.pathname);

/**
* isResizedCatalogImage is route checker for workbox
* that returns true for a valid catalog image URL.
* isResizedImage is route checker for workbox
* that returns true for a valid resized image URL.
*
* @param {url: URL, event: FetchEvent} workboxRouteObject
*
* @returns {boolean}
*/
export const isResizedCatalogImage = ({ url }) =>
isCatalogImage({ url }) && !isNaN(getWidth(url));
export const isResizedImage = ({ url }) =>
isImage(url) && !isNaN(getWidth(url));

/**
* This function tries to find same or a larger image
* from the catalog cache storage.
* from the images cache storage.
*
* @param {URL} url
*
Expand All @@ -36,7 +38,7 @@ export const findSameOrLargerImage = async url => {
const requestedWidth = getWidth(url);
const requestedFilename = url.pathname.split('/').reverse()[0];

const cache = await caches.open(CATALOG_CACHE_NAME);
const cache = await caches.open(IMAGES_CACHE_NAME);
const cachedURLs = await cache.keys();
const cachedSources = await cachedURLs.filter(({ url }) => {
const cachedFileName = new URL(url).pathname.split('/').reverse()[0];
Expand Down Expand Up @@ -101,7 +103,7 @@ export const findSameOrLargerImage = async url => {
const fetchAndCacheImage = imageURL =>
fetch(imageURL, { mode: 'no-cors' }).then(response =>
caches
.open(CATALOG_CACHE_NAME)
.open(IMAGES_CACHE_NAME)
.then(cache => cache.put(imageURL, response.clone()))
.then(() => response)
);
Expand Down Expand Up @@ -152,11 +154,11 @@ export const registerImagePreFetchHandler = () => {

/**
* This function creates a handler that workbox can use
* to handle all catalog images.
* to handle all images.
*/
export const createCatalogCacheHandler = () =>
export const createImageCacheHandler = () =>
new CacheFirst({
cacheName: CATALOG_CACHE_NAME,
cacheName: IMAGES_CACHE_NAME,
plugins: [
new ExpirationPlugin({
maxEntries: 60,
Expand Down
19 changes: 16 additions & 3 deletions src/ServiceWorker/Utilities/routeHandler.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
/**
* Checks if the given URL object belongs to the home route `/`.
* Checks if the given URL object belongs to the home route.
*
* @param {URL} url
*
* @returns {boolean}
*/
export const isHomeRoute = url => url.pathname === '/';
export const isHomeRoute = url => {
if (url.pathname === '/') {
return true;
}

// If store code is in the url, the home route will be url.com/view_code.
// A trailing / may or may not follow.
if (process.env.USE_STORE_CODE_IN_URL === 'true') {
return AVAILABLE_STORE_VIEWS.some(
({ code }) =>
url.pathname === `/${code}/` || url.pathname === `/${code}`
);
}
};

/**
* Checks if the given URL object belongs to the home route `/`
Expand All @@ -16,4 +29,4 @@ export const isHomeRoute = url => url.pathname === '/';
* @returns {boolean}
*/
export const isHTMLRoute = url =>
isHomeRoute(url) || new RegExp('.html$').test(url.pathname);
isHomeRoute(url) || new RegExp('\\.html$').test(url.pathname);
2 changes: 1 addition & 1 deletion src/ServiceWorker/defaults.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export const THIRTY_DAYS = 30 * 24 * 60 * 60;

export const CATALOG_CACHE_NAME = 'catalog';
export const IMAGES_CACHE_NAME = 'images';

export const MAX_NUM_OF_IMAGES_TO_CACHE = 60;
24 changes: 15 additions & 9 deletions src/ServiceWorker/registerRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ import { ExpirationPlugin } from 'workbox-expiration';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, StaleWhileRevalidate } from 'workbox-strategies';
import {
isResizedCatalogImage,
isResizedImage,
findSameOrLargerImage,
createCatalogCacheHandler
createImageCacheHandler
} from './Utilities/imageCacheHandler';
import { isHTMLRoute } from './Utilities/routeHandler';
import { THIRTY_DAYS, MAX_NUM_OF_IMAGES_TO_CACHE } from './defaults';
import {
THIRTY_DAYS,
MAX_NUM_OF_IMAGES_TO_CACHE,
IMAGES_CACHE_NAME
} from './defaults';

/**
* registerRoutes function contains all the routes that need to
Expand All @@ -17,34 +21,36 @@ import { THIRTY_DAYS, MAX_NUM_OF_IMAGES_TO_CACHE } from './defaults';
* @returns {void}
*/
export default function() {
const catalogCacheHandler = createCatalogCacheHandler();
const imageCacheHandler = createImageCacheHandler();

registerRoute(
new RegExp('(robots.txt|favicon.ico|manifest.json)'),
new StaleWhileRevalidate()
);

/**
* Route that checks for resized catalog images in cache.
* Route that checks for resized images in cache.
*/
registerRoute(isResizedCatalogImage, ({ url, request, event }) => {
registerRoute(isResizedImage, ({ url, request, event }) => {
const sameOrLargerImagePromise = findSameOrLargerImage(url, request);
event.waitUntil(sameOrLargerImagePromise);
return sameOrLargerImagePromise.then(
response =>
response || catalogCacheHandler.handle({ request, event })
response => response || imageCacheHandler.handle({ request, event })
);
});

/**
* Route to handle all types of images. Stores them in cache with a
* cache name "images". They auto expire after 30 days and only 60
* can be stored at a time.
*
* There is another route that handles images without width and options on them.
* This route handles images that wont have width options on them.
*/
registerRoute(
/\.(?:png|gif|jpg|jpeg|svg)$/,
new CacheFirst({
cacheName: 'images',
cacheName: IMAGES_CACHE_NAME,
plugins: [
new ExpirationPlugin({
maxEntries: MAX_NUM_OF_IMAGES_TO_CACHE, // 60 Images
Expand Down
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
store: STORE_VIEW_CODE,
authorization: token ? `Bearer ${token}` : ''
}
};
Expand Down Expand Up @@ -107,6 +106,7 @@ const apolloLink = ApolloLink.from([
}
}),
authLink,
Adapter.storeLink,
errorLink,
// An apollo-link-http Link
Adapter.apolloLink(apiBase)
Expand Down
Loading

0 comments on commit e5c92ea

Please sign in to comment.