Browse Source

WIP: disabling absurd-sql when using Capacitor SQLite

pull/137/head
Matthew Raymer 2 weeks ago
parent
commit
b18112b869
  1. 86
      scripts/build-electron.js
  2. 6
      src/main.web.ts
  3. 25
      src/registerServiceWorker.ts
  4. 11
      vite.config.common.mts
  5. 56
      vite.config.electron.mts

86
scripts/build-electron.js

@ -1,9 +1,9 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
console.log('Starting electron build process...'); console.log('Starting electron build process...');
// Copy web files // Define paths
const webDistPath = path.join(__dirname, '..', 'dist'); const webDistPath = path.join(__dirname, '..', 'dist');
const electronDistPath = path.join(__dirname, '..', 'dist-electron'); const electronDistPath = path.join(__dirname, '..', 'dist-electron');
const wwwPath = path.join(electronDistPath, 'www'); const wwwPath = path.join(electronDistPath, 'www');
@ -16,20 +16,94 @@ if (!fs.existsSync(wwwPath)) {
// Copy web files to www directory // Copy web files to www directory
fs.cpSync(webDistPath, wwwPath, { recursive: true }); fs.cpSync(webDistPath, wwwPath, { recursive: true });
// Fix asset paths in index.html // Remove service worker files
const swFilesToRemove = [
'sw.js',
'sw.js.map',
'workbox-*.js',
'workbox-*.js.map',
'registerSW.js',
'manifest.webmanifest',
'**/workbox-*.js',
'**/workbox-*.js.map',
'**/sw.js',
'**/sw.js.map',
'**/registerSW.js',
'**/manifest.webmanifest'
];
console.log('Removing service worker files...');
swFilesToRemove.forEach(pattern => {
const files = fs.readdirSync(wwwPath).filter(file =>
file.match(new RegExp(pattern.replace(/\*/g, '.*')))
);
files.forEach(file => {
const filePath = path.join(wwwPath, file);
console.log(`Removing ${filePath}`);
try {
fs.unlinkSync(filePath);
} catch (err) {
console.warn(`Could not remove ${filePath}:`, err.message);
}
});
});
// Also check and remove from assets directory
const assetsPath = path.join(wwwPath, 'assets');
if (fs.existsSync(assetsPath)) {
swFilesToRemove.forEach(pattern => {
const files = fs.readdirSync(assetsPath).filter(file =>
file.match(new RegExp(pattern.replace(/\*/g, '.*')))
);
files.forEach(file => {
const filePath = path.join(assetsPath, file);
console.log(`Removing ${filePath}`);
try {
fs.unlinkSync(filePath);
} catch (err) {
console.warn(`Could not remove ${filePath}:`, err.message);
}
});
});
}
// Modify index.html to remove service worker registration
const indexPath = path.join(wwwPath, 'index.html'); const indexPath = path.join(wwwPath, 'index.html');
let indexContent = fs.readFileSync(indexPath, 'utf8'); if (fs.existsSync(indexPath)) {
console.log('Modifying index.html to remove service worker registration...');
let indexContent = fs.readFileSync(indexPath, 'utf8');
// Remove service worker registration script
indexContent = indexContent
.replace(/<script[^>]*id="vite-plugin-pwa:register-sw"[^>]*><\/script>/g, '')
.replace(/<script[^>]*registerServiceWorker[^>]*><\/script>/g, '')
.replace(/<link[^>]*rel="manifest"[^>]*>/g, '')
.replace(/<link[^>]*rel="serviceworker"[^>]*>/g, '')
.replace(/navigator\.serviceWorker\.register\([^)]*\)/g, '')
.replace(/if\s*\(\s*['"]serviceWorker['"]\s*in\s*navigator\s*\)\s*{[^}]*}/g, '');
fs.writeFileSync(indexPath, indexContent);
console.log('Successfully modified index.html');
}
// Fix asset paths // Fix asset paths
indexContent = indexContent console.log('Fixing asset paths in index.html...');
let indexContent = fs.readFileSync(indexPath, 'utf8');
indexContent = indexContent
.replace(/\/assets\//g, './assets/') .replace(/\/assets\//g, './assets/')
.replace(/href="\//g, 'href="./') .replace(/href="\//g, 'href="./')
.replace(/src="\//g, 'src="./'); .replace(/src="\//g, 'src="./');
fs.writeFileSync(indexPath, indexContent); fs.writeFileSync(indexPath, indexContent);
// Verify no service worker references remain
const finalContent = fs.readFileSync(indexPath, 'utf8');
if (finalContent.includes('serviceWorker') || finalContent.includes('workbox')) {
console.warn('Warning: Service worker references may still exist in index.html');
}
// Check for remaining /assets/ paths // Check for remaining /assets/ paths
console.log('After path fixing, checking for remaining /assets/ paths:', indexContent.includes('/assets/')); console.log('After path fixing, checking for remaining /assets/ paths:', indexContent.includes('/assets/'));
console.log('Sample of fixed content:', indexContent.substring(0, 500)); console.log('Sample of fixed content:', indexContent.substring(0, 500));
console.log('Copied and fixed web files in:', wwwPath); console.log('Copied and fixed web files in:', wwwPath);

6
src/main.web.ts

@ -1,7 +1,11 @@
// @ts-expect-error but not sure why it's not in there // @ts-expect-error but not sure why it's not in there
import { initBackend } from "absurd-sql/dist/indexeddb-main-thread"; import { initBackend } from "absurd-sql/dist/indexeddb-main-thread";
import { initializeApp } from "./main.common"; import { initializeApp } from "./main.common";
import "./registerServiceWorker"; // Web PWA support
// Only import service worker for web builds
if (process.env.VITE_PLATFORM !== 'electron' && process.env.VITE_PWA_ENABLED === 'true') {
import("./registerServiceWorker"); // Web PWA support
}
const app = initializeApp(); const app = initializeApp();

25
src/registerServiceWorker.ts

@ -2,11 +2,18 @@
import { register } from "register-service-worker"; import { register } from "register-service-worker";
// Only register service worker if explicitly enabled and in production // Check if we're in an Electron environment
if ( const isElectron = process.env.VITE_PLATFORM === 'electron' ||
process.env.VITE_PWA_ENABLED === "true" && process.env.VITE_DISABLE_PWA === 'true' ||
process.env.NODE_ENV === "production" window.navigator.userAgent.toLowerCase().includes('electron');
) {
// Only register service worker if:
// 1. Not in Electron
// 2. PWA is explicitly enabled
// 3. In production mode
if (!isElectron &&
process.env.VITE_PWA_ENABLED === "true" &&
process.env.NODE_ENV === "production") {
register(`${process.env.BASE_URL}sw.js`, { register(`${process.env.BASE_URL}sw.js`, {
ready() { ready() {
console.log("Service worker is active."); console.log("Service worker is active.");
@ -34,6 +41,12 @@ if (
}); });
} else { } else {
console.log( console.log(
"Service worker registration skipped - not enabled or not in production", `Service worker registration skipped - ${
isElectron
? "running in Electron"
: process.env.VITE_PWA_ENABLED !== "true"
? "PWA not enabled"
: "not in production mode"
}`
); );
} }

11
vite.config.common.mts

@ -17,8 +17,10 @@ export async function createBuildConfig(mode: string): Promise<UserConfig> {
const isCapacitor = mode === "capacitor"; const isCapacitor = mode === "capacitor";
const isPyWebView = mode === "pywebview"; const isPyWebView = mode === "pywebview";
// Explicitly set platform // Explicitly set platform and disable PWA for Electron
process.env.VITE_PLATFORM = mode; process.env.VITE_PLATFORM = mode;
process.env.VITE_PWA_ENABLED = isElectron ? 'false' : 'true';
process.env.VITE_DISABLE_PWA = isElectron ? 'true' : 'false';
if (isElectron || isPyWebView || isCapacitor) { if (isElectron || isPyWebView || isCapacitor) {
process.env.VITE_PWA_ENABLED = 'false'; process.env.VITE_PWA_ENABLED = 'false';
@ -55,7 +57,8 @@ export async function createBuildConfig(mode: string): Promise<UserConfig> {
define: { define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.VITE_PLATFORM': JSON.stringify(mode), 'process.env.VITE_PLATFORM': JSON.stringify(mode),
'process.env.VITE_PWA_ENABLED': JSON.stringify(!(isElectron || isPyWebView || isCapacitor)), 'process.env.VITE_PWA_ENABLED': JSON.stringify(!isElectron),
'process.env.VITE_DISABLE_PWA': JSON.stringify(isElectron),
__dirname: isElectron ? JSON.stringify(process.cwd()) : '""', __dirname: isElectron ? JSON.stringify(process.cwd()) : '""',
__IS_MOBILE__: JSON.stringify(isCapacitor), __IS_MOBILE__: JSON.stringify(isCapacitor),
__USE_QR_READER__: JSON.stringify(!isCapacitor), __USE_QR_READER__: JSON.stringify(!isCapacitor),
@ -97,7 +100,9 @@ export async function createBuildConfig(mode: string): Promise<UserConfig> {
'register-service-worker', 'register-service-worker',
'workbox-window', 'workbox-window',
'web-push', 'web-push',
'serviceworker-webpack-plugin' 'serviceworker-webpack-plugin',
'vite-plugin-pwa',
'@vite-pwa/vue'
] : [] ] : []
} }
}; };

56
vite.config.electron.mts

@ -53,24 +53,46 @@ export default defineConfig(async () => {
} }
}, },
{ {
name: 'remove-sw-imports', name: 'remove-sw-imports',
transform(code: string, id: string) { transform(code: string, id: string) {
if ( // Remove service worker imports and registrations
id.includes('registerServiceWorker') || if (id.includes('registerServiceWorker') ||
id.includes('register-service-worker') || id.includes('register-service-worker') ||
id.includes('sw_scripts') || id.includes('sw_scripts') ||
id.includes('PushNotificationPermission') || id.includes('PushNotificationPermission') ||
code.includes('navigator.serviceWorker') code.includes('navigator.serviceWorker')) {
) { return {
return { code: code
code: code .replace(/import.*registerServiceWorker.*$/mg, '')
.replace(/import.*registerServiceWorker.*$/mg, '') .replace(/import.*register-service-worker.*$/mg, '')
.replace(/import.*register-service-worker.*$/mg, '') .replace(/navigator\.serviceWorker/g, 'undefined')
.replace(/navigator\.serviceWorker/g, 'undefined') .replace(/if\s*\([^)]*serviceWorker[^)]*\)\s*{[^}]*}/g, '')
.replace(/if\s*\([^)]*serviceWorker[^)]*\)\s*{[^}]*}/g, '') .replace(/import.*workbox.*$/mg, '')
}; .replace(/importScripts\([^)]*\)/g, '')
};
}
return code;
}
},
{
name: 'remove-sw-files',
enforce: 'pre',
resolveId(id: string) {
// Prevent service worker files from being included
if (id.includes('sw.js') ||
id.includes('workbox') ||
id.includes('registerSW.js') ||
id.includes('manifest.webmanifest')) {
return '\0empty';
}
return null;
},
load(id: string) {
if (id === '\0empty') {
return 'export default {}';
}
return null;
} }
}
} }
], ],
ssr: { ssr: {

Loading…
Cancel
Save