Skip to content

Commit

Permalink
Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
blittle committed Nov 28, 2022
1 parent 9467473 commit a3485af
Show file tree
Hide file tree
Showing 11 changed files with 253 additions and 94 deletions.
33 changes: 28 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions packages/hydrogen-remix/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@
"default": "./dist/production/index.js"
}
},
"./build": {
"types": "./dist/production/build.d.ts",
"module": {
"development": "./dist/development/build.js",
"default": "./dist/production/build.js"
},
"require": "./dist/build.cjs",
"import": {
"development": "./dist/development/build.js",
"default": "./dist/production/build.js"
},
"default": {
"development": "./dist/development/build.js",
"default": "./dist/production/build.js"
}
},
"./package.json": "./package.json"
},
"files": [
Expand All @@ -37,5 +53,11 @@
"@remix-run/oxygen": "*",
"@remix-run/react": "*",
"@shopify/hydrogen": "*"
},
"dependencies": {
"recursive-readdir": "^2.2.3"
},
"devDependencies": {
"@types/recursive-readdir": "^2.2.1"
}
}
1 change: 1 addition & 0 deletions packages/hydrogen-remix/src/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {hydrogenRoutes} from './routing/routes';
93 changes: 93 additions & 0 deletions packages/hydrogen-remix/src/routing/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import fs from 'fs';
import esbuild from 'esbuild';
import readDir from 'recursive-readdir';
import path from 'path';

export type HydrogenRouteOptions = {
prefixLocalizedRoutes?: boolean;
};

export async function hydrogenRoutes(
defineRoutes: any,
options: HydrogenRouteOptions = {},
) {
if (options.prefixLocalizedRoutes) {
await buildLangRoutes();
}

const templatesPath = path.resolve(__dirname, '../../templates');

// fs.copyFileSync(templatesPath)

// const templates = await readDir(templatesPath);

// for (const template of templates) {
// console.log(template);
// }

// @todo - extract into packaged helper function
// @todo - add logic for i18n
// const appRoutesPath = path.resolve(
// '../../templates/demo-store',
// 'app/routes',
// );
// @todo - generalize from `path.cwd()`
// const appRouteFiles = await readDir(appRoutesPath);
const hydrogenRoutesPath = path.resolve(process.cwd(), '.hydrogen/routes');
const hydrogenRouteFiles = await readDir(hydrogenRoutesPath);
return defineRoutes((route: any) => {
for (const hydrogenRoute of hydrogenRouteFiles) {
const hydrogenRoutePath = path.relative(process.cwd(), hydrogenRoute);

const hydrogenRouteUrl = hydrogenRoutePath.substring(
hydrogenRoutePath.lastIndexOf('/'),
hydrogenRoutePath.lastIndexOf('.'),
);

route(hydrogenRouteUrl, '../' + hydrogenRoutePath);
}
});
}

async function buildLangRoutes() {
const appDir = path.resolve(process.cwd(), 'app');
const routesDir = path.resolve(appDir, 'routes');
const langDir = path.resolve(routesDir, '$lang');

const files = await readDir(routesDir, [
(file) => {
return !!file.replace(/\\/g, '/').match(/routes\/\$lang\//);
},
]);

// eslint-disable-next-line no-console
console.log(`Duplicating ${files.length} route(s) for translations`);

for (let file of files) {
let bundle = await esbuild.build({
entryPoints: {entry: file},
bundle: false,
metafile: true,
write: false,
});

const moduleExports = bundle?.metafile?.outputs['entry.js'].exports;

const moduleId =
'~/' +
path
.relative(appDir, file)
.replace(/\\/g, '/')
.slice(0, -path.extname(file).length);

const outFile = path.resolve(langDir, path.relative(routesDir, file));

fs.mkdirSync(path.dirname(outFile), {recursive: true});
fs.writeFileSync(
outFile,
`export {${moduleExports!.join(', ')}} from ${JSON.stringify(
moduleId,
)};\n`,
);
}
}
3 changes: 3 additions & 0 deletions packages/hydrogen-remix/templates/routes/__health.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export async function loader() {
return new Response(null, {status: 200});
}
6 changes: 6 additions & 0 deletions packages/hydrogen-remix/templates/routes/admin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {LoaderArgs, redirect} from '@shopify/hydrogen-remix';

export async function loader({context}: LoaderArgs) {
const domain = context.storefront.getShopifyDomain();
return redirect(domain + '/admin');
}
45 changes: 45 additions & 0 deletions packages/hydrogen-remix/templates/routes/graphiql.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {LoaderArgs} from '@shopify/hydrogen-remix';

export async function loader({context}: LoaderArgs) {
const url = context.storefront.getStorefrontApiUrl();
const privateToken =
context.storefront.getPublicTokenHeaders()[
'X-Shopify-Storefront-Access-Token'
];

return new Response(
`
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<title>Shopify Storefront API</title>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/css/index.css" />
<link rel="shortcut icon" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/favicon.png" />
<script src="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/js/middleware.js"></script>
</head>
<body>
<div id="root"></div>
<script>window.addEventListener('load', function (event) {
GraphQLPlayground.init(document.getElementById('root'), {
endpoint: '${url}',
settings:{
'request.globalHeaders': {
Accept: 'application/json',
'Content-Type': 'application/graphql',
'X-Shopify-Storefront-Access-Token': '${privateToken}'
}
},
tabs: [{
endpoint: '${url}',
query: '{ shop { name } }'
}]
})
})</script>
</body>
</html>
`,
{status: 200, headers: {'content-type': 'text/html'}},
);
}
45 changes: 45 additions & 0 deletions packages/hydrogen-remix/templates/routes/route-manifest.json.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import * as build from '@remix-run/dev/server-build';
import {RESOURCE_TYPES, REQUIRED_RESOURCES} from '@shopify/hydrogen-remix';

type RESOURCE_TYPE = keyof typeof RESOURCE_TYPES;

type LoaderOutput = {
customRoutes: Array<{pathname: string}>;
resourceRoutes: Array<{pathname: string; type: RESOURCE_TYPE}>;
};

export async function loader() {
const outputJSON: LoaderOutput = {
customRoutes: [],
resourceRoutes: [],
};

for (const [routeId, route] of Object.entries(build.routes)) {
const {resourceType} = route.module?.handle?.hydrogen ?? {};

if (!resourceType && route.path) {
outputJSON.customRoutes.push({
pathname: route.path,
});
continue;
}

if (!RESOURCE_TYPES[resourceType as RESOURCE_TYPE]) {
console.warn(
`Unknown resource type on route ${route.id}: ${resourceType}`,
);
continue;
}

if (route.path) {
outputJSON.resourceRoutes.push({
type: resourceType,
pathname: route.path,
});
}
}

// @todo warn if required resources are not defined!

return outputJSON;
}
1 change: 0 additions & 1 deletion templates/demo-store/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
"postcss-import": "^15.0.0",
"postcss-preset-env": "^7.8.2",
"prettier": "^2.7.1",
"recursive-readdir": "^2.2.3",
"rimraf": "^3.0.2",
"tailwindcss": "^3.1.8",
"typescript": "^4.8.3"
Expand Down
Loading

0 comments on commit a3485af

Please sign in to comment.