diff --git a/Dockerfile b/Dockerfile index f882bca8..f63f9bf4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,21 +5,17 @@ ENV NODE_ENV production RUN npm install -g pnpm -FROM base as deps +FROM base as build WORKDIR /app -ADD package.json pnpm-lock.yaml pnpm-workspace.yaml . -ADD packages ./packages -ADD apps/web/package.json ./apps/web/package.json -ADD apps/api/package.json ./apps/api/package.json +ADD . . +# ADD package.json pnpm-lock.yaml pnpm-workspace.yaml . +# ADD packages ./packages +# ADD apps/web/package.json ./apps/web/package.json +# ADD apps/api/package.json ./apps/api/package.json RUN pnpm install -# build web -FROM base as build-web - -WORKDIR /app - ARG VERSION ENV VERSION $VERSION @@ -38,32 +34,14 @@ ENV API_SERVER $API_SERVER ARG GOOGLE_CLIENT_ID ENV GOOGLE_CLIENT_ID $GOOGLE_CLIENT_ID -COPY --from=deps /app/node_modules ./node_modules -COPY --from=deps /app/apps/web/node_modules ./node_modules -COPY --from=deps /app/packages/shared ./node_modules/@peated/shared -ADD apps/web/ . - RUN --mount=type=secret,id=SENTRY_AUTH_TOKEN \ SENTRY_AUTH_TOKEN="$(cat /run/secrets/SENTRY_AUTH_TOKEN)" \ - npm run build - -# build api -FROM base as build-api - -WORKDIR /app - -COPY --from=deps /app/node_modules ./node_modules -COPY --from=deps /app/apps/api/node_modules ./node_modules -COPY --from=deps /app/packages/shared ./node_modules/@peated/shared - -ADD apps/api/ . - -RUN npm run build + pnpm build # web service FROM nginx:alpine as web -COPY --from=build-web /app/dist /usr/share/nginx/html +COPY --from=build /app/dist /usr/share/nginx/html RUN rm /etc/nginx/conf.d/default.conf @@ -74,13 +52,11 @@ EXPOSE 8043 CMD ["nginx", "-g", "daemon off;"] # api service -FROM build-api as api +FROM build as api WORKDIR /app -COPY --from=build-api /app/node_modules ./node_modules - -ADD apps/api/ . +COPY --from=build /app/ ./ ARG VERSION ENV VERSION $VERSION @@ -92,4 +68,6 @@ ENV PORT 4000 EXPOSE 4000 -CMD ["npm", "start"] +WORKDIR /app/apps/api + +CMD ["pnpm", "start"] diff --git a/apps/web/package.json b/apps/web/package.json index eda729e2..3af2103d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -42,7 +42,8 @@ "workbox-range-requests": "^6.5.4", "workbox-routing": "^6.5.4", "workbox-strategies": "^6.5.4", - "workbox-streams": "^6.5.4" + "workbox-streams": "^6.5.4", + "workbox-window": "^6.5.4" }, "proxy": "http://localhost:4000", "scripts": { diff --git a/apps/web/src/config.tsx b/apps/web/src/config.tsx index 9354f386..d5a68c96 100644 --- a/apps/web/src/config.tsx +++ b/apps/web/src/config.tsx @@ -1,11 +1,11 @@ const config = { ENV: import.meta.env.PROD ? "production" : "development", DEBUG: import.meta.env.DEV, - GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID || "", - SENTRY_DSN: process.env.SENTRY_DSN || "", - API_SERVER: process.env.API_SERVER || "http://localhost:4000", + GOOGLE_CLIENT_ID: import.meta.env.GOOGLE_CLIENT_ID || "", + SENTRY_DSN: import.meta.env.SENTRY_DSN || "", + API_SERVER: import.meta.env.API_SERVER || "http://localhost:4000", - VERSION: process.env.VERSION || "", + VERSION: import.meta.env.VERSION || "", GITHUB_REPO: "https://github.com/dcramer/peated", }; diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index bc1e789e..ce87e36a 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -16,7 +16,6 @@ import createRoutes from "./routes"; import config from "./config"; import { AuthProvider } from "./hooks/useAuth"; import { OnlineStatusProvider } from "./hooks/useOnlineStatus"; -import { register } from "./serviceWorkerRegistration"; import Spinner from "./components/spinner"; Sentry.init({ @@ -95,8 +94,3 @@ root.render( ); - -// If you want your app to work offline and load faster, you can change -// unregister() to register() below. Note this comes with some pitfalls. -// Learn more about service workers: https://cra.link/PWA -register(); diff --git a/apps/web/src/service-worker.ts b/apps/web/src/service-worker.ts deleted file mode 100644 index 652a8a4a..00000000 --- a/apps/web/src/service-worker.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// -/* eslint-disable no-restricted-globals */ - -// This service worker can be customized! -// See https://developers.google.com/web/tools/workbox/modules -// for the list of available Workbox modules, or add any other -// code you'd like. -// You can also remove this file if you'd prefer not to use a -// service worker, and the Workbox build step will be skipped. - -import { clientsClaim } from 'workbox-core'; -import { ExpirationPlugin } from 'workbox-expiration'; -import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching'; -import { registerRoute } from 'workbox-routing'; -import { StaleWhileRevalidate } from 'workbox-strategies'; - -declare const self: ServiceWorkerGlobalScope; - -clientsClaim(); - -// Precache all of the assets generated by your build process. -// Their URLs are injected into the manifest variable below. -// This variable must be present somewhere in your service worker file, -// even if you decide not to use precaching. See https://cra.link/PWA -precacheAndRoute(self.__WB_MANIFEST); - -// Set up App Shell-style routing, so that all navigation requests -// are fulfilled with your index.html shell. Learn more at -// https://developers.google.com/web/fundamentals/architecture/app-shell -const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$'); -registerRoute( - // Return false to exempt requests from being fulfilled by index.html. - ({ request, url }: { request: Request; url: URL }) => { - // If this isn't a navigation, skip. - if (request.mode !== 'navigate') { - return false; - } - - // If this is a URL that starts with /_, skip. - if (url.pathname.startsWith('/_')) { - return false; - } - - // If this looks like a URL for a resource, because it contains - // a file extension, skip. - if (url.pathname.match(fileExtensionRegexp)) { - return false; - } - - // Return true to signal that we want to use the handler. - return true; - }, - createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html') -); - -// An example runtime caching route for requests that aren't handled by the -// precache, in this case same-origin .png requests like those from in public/ -registerRoute( - // Add in any other file extensions or routing criteria as needed. - ({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), - // Customize this strategy as needed, e.g., by changing to CacheFirst. - new StaleWhileRevalidate({ - cacheName: 'images', - plugins: [ - // Ensure that once this runtime cache reaches a maximum size the - // least-recently used images are removed. - new ExpirationPlugin({ maxEntries: 50 }), - ], - }) -); - -// This allows the web app to trigger skipWaiting via -// registration.waiting.postMessage({type: 'SKIP_WAITING'}) -self.addEventListener('message', (event) => { - if (event.data && event.data.type === 'SKIP_WAITING') { - self.skipWaiting(); - } -}); - -// Any other custom service worker logic can go here. diff --git a/apps/web/src/serviceWorkerRegistration.ts b/apps/web/src/serviceWorkerRegistration.ts deleted file mode 100644 index 1f13cdeb..00000000 --- a/apps/web/src/serviceWorkerRegistration.ts +++ /dev/null @@ -1,150 +0,0 @@ -// This optional code is used to register a service worker. -// register() is not called by default. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on subsequent visits to a page, after all the -// existing tabs open on the page have been closed, since previously cached -// resources are updated in the background. - -// To learn more about the benefits of this model and instructions on how to -// opt-in, read https://cra.link/PWA - -const isLocalhost = Boolean( - window.location.hostname === "localhost" || - // [::1] is the IPv6 localhost address. - window.location.hostname === "[::1]" || - // 127.0.0.0/8 are considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -type Config = { - onSuccess?: (registration: ServiceWorkerRegistration) => void; - onUpdate?: (registration: ServiceWorkerRegistration) => void; -}; - -export function register(config?: Config) { - if ( - process.env.NODE_ENV === "production" && - "serviceWorker" in navigator && - process.env.PUBLIC_URL - ) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebook/create-react-app/issues/2374 - return; - } - - window.addEventListener("load", () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log( - "This web app is being served cache-first by a service " + - "worker. To learn more, visit https://cra.link/PWA" - ); - }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } -} - -function registerValidSW(swUrl: string, config?: Config) { - navigator.serviceWorker - .register(swUrl) - .then((registration) => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === "installed") { - if (navigator.serviceWorker.controller) { - // At this point, the updated precached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - "New content is available and will be used when all " + - "tabs for this page are closed. See https://cra.link/PWA." - ); - - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log("Content is cached for offline use."); - - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch((error) => { - console.error("Error during service worker registration:", error); - }); -} - -function checkValidServiceWorker(swUrl: string, config?: Config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl, { - headers: { "Service-Worker": "script" }, - }) - .then((response) => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get("content-type"); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf("javascript") === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then((registration) => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - "No internet connection found. App is running in offline mode." - ); - }); -} - -export function unregister() { - if ("serviceWorker" in navigator) { - navigator.serviceWorker.ready - .then((registration) => { - registration.unregister(); - }) - .catch((error) => { - console.error(error.message); - }); - } -} diff --git a/apps/web/vite-env.d.ts b/apps/web/vite-env.d.ts index dc17bfe2..64a748e9 100644 --- a/apps/web/vite-env.d.ts +++ b/apps/web/vite-env.d.ts @@ -6,12 +6,21 @@ /// interface ImportMetaEnv { - readonly VITE_GOOGLE_CLIENT_ID: string; - readonly VITE_SENTRY_DSN: string; - readonly VITE_API_SERVER: string; - readonly VITE_API_SERVER: string; + readonly GOOGLE_CLIENT_ID: string; + readonly SENTRY_DSN: string; + readonly API_SERVER: string; + readonly VERSION: string; } interface ImportMeta { readonly env: ImportMetaEnv; } + +declare namespace NodeJS { + export interface ProcessEnv { + NODE_ENV: "development" | "production" | "test"; + SENTRY_DSN?: string; + API_SERVER?: string; + VERSION?: string; + } +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index ca555912..15ac9703 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -71,13 +71,13 @@ if (selfDestroying) pwaOptions.selfDestroying = selfDestroying; const ALLOWED_ENV = ["SENTRY_DSN", "GOOGLE_CLIENT_ID", "API_SERVER", "VERSION"]; // https://vitejs.dev/config/ -export default defineConfig(({ command, mode }) => { +export default defineConfig(({ mode }) => { // Load env file based on `mode` in the current working directory. // Set the third parameter to '' to load all env regardless of the `VITE_` prefix. const env = loadEnv(mode, process.cwd(), ""); const processEnvValues = { - "process.env": Object.entries(env) + "import.meta.env": Object.entries(env) .filter(([k]) => ALLOWED_ENV.indexOf(k)) .reduce((prev, [key, val]) => { return { diff --git a/package.json b/package.json index 22e1534f..315c4f51 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,8 @@ "build": "pnpm -r --filter='./apps/**' run build", "setup": "pnpm install && npm run db:migrate", "dev": "nf start", + "dev:web": "API_SERVER=http://localhost:4000 dotenv -e .env.local -- pnpm --filter='./apps/web' dev", + "dev:api": "PORT=4000 dotenv -e .env.local -- pnpm --filter='./apps/api' dev", "db:migrate": "dotenv -e .env.local -- pnpm --filter='./apps/api' db:migrate", "typecheck": "tsc --noEmit", "test": "pnpm -r --stream run test",