Skip to content
This repository was archived by the owner on Sep 26, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions electron/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
3 changes: 3 additions & 0 deletions electron/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
src
rollup.config.js
tsconfig.json
12 changes: 12 additions & 0 deletions electron/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default {
input: 'electron/build/index.js',
output: [
{
file: 'electron/dist/plugin.js',
format: 'cjs',
sourcemap: true,
inlineDynamicImports: true,
},
],
external: ['@capacitor/core'],
};
134 changes: 134 additions & 0 deletions electron/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import fetch, { Response, RequestInfo, RequestInit } from 'node-fetch';
import { EventEmitter } from 'stream';
import { randomBytes } from 'crypto';

type ReturnType = Response & {
headers: { [k: string]: string };
url: string;
id: string;
};

interface BodyEvents {
error: (error: Error) => void;
data: (data: any) => void;
close: () => void;
}

class FetchHelper extends EventEmitter {
private static _responses = new Map<
string,
{ response: Response; bodyEvents?: BodyEvents }
>();

async fetch(url: RequestInfo, init?: RequestInit): Promise<ReturnType> {
const response = await fetch(url, init);

return FetchHelper._cloneResponse(response);
}

async getBuffer(id: string): Promise<Buffer> {
const response = await FetchHelper._getResponse(id);

return response.response.buffer();
}
async getText(id: string): Promise<string> {
const response = await FetchHelper._getResponse(id);

return response.response.text();
}
async getJson(id: string): Promise<Record<string, any>> {
const response = await FetchHelper._getResponse(id);

return response.response.json();
}
async getBlob(id: string): Promise<{ type: string; buffer: Buffer }> {
const response = await FetchHelper._getResponse(id);
const blob = await response.response.blob();

const buffer = Buffer.from(await blob.text(), 'utf-8');

return {
type: blob.type,
buffer,
};
}

async startBodyStream(id: string): Promise<void> {
const response = await FetchHelper._getResponse(id, false);

const eventHandlers: BodyEvents = {
error: err => {
this.emit(`body-${id}`, 'error', err);
},
data: data => {
this.emit(`body-${id}`, 'data', data);
},
close: () => {
this.emit(`body-${id}`, 'close');
this.stopBodyStream(id);
},
};

response.response.body.on('close', eventHandlers.close);
response.response.body.on('error', eventHandlers.error);
response.response.body.on('data', eventHandlers.data);

response.bodyEvents = eventHandlers;
}
async stopBodyStream(id: string): Promise<void> {
const response = await FetchHelper._getResponse(id);

Object.entries(response.bodyEvents ?? {}).forEach(([key, value]) => {
response.response.body.off(key, value);
});
}

dispose(id: string): void {
FetchHelper._dispose(id);
}

private static _cloneResponse(response: Response): ReturnType {
const headers = Object.fromEntries([...response.headers.entries()]);
const id = FetchHelper._id();

FetchHelper._responses.set(id, { response, bodyEvents: undefined });

return {
...response,

redirected: response.redirected,
statusText: response.statusText,
status: response.status,
url: response.url,
ok: response.ok,
headers,

id,
} as ReturnType;
}

private static _id() {
return randomBytes(8).toString('hex');
}

private static _dispose(id: string): void {
FetchHelper._responses.delete(id);
}

private static _getResponse(
id: string,
dispose = true,
): Promise<{ response: Response; bodyEvents?: BodyEvents }> {
const response = FetchHelper._responses.get(id);

if (dispose) {
FetchHelper._dispose(id);
}

return response
? Promise.resolve(response)
: Promise.reject(new Error(`Response not found for ID '${id}'`));
}
}

export { FetchHelper as Fetch, ReturnType };
19 changes: 19 additions & 0 deletions electron/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"experimentalDecorators": true,
"noEmitHelpers": true,
"importHelpers": true,
"lib": ["dom", "es2020"],
"module": "commonjs",
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"outDir": "build",
"sourceMap": true,
"strict": false,
"target": "ES2017"
},
"include": ["src/**/*"]
}
6 changes: 6 additions & 0 deletions example/capacitor.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"appId": "com.example.app",
"appName": "http-example",
"webDir": "www",
"bundledWebRuntime": false
}
10 changes: 10 additions & 0 deletions example/electron/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# NPM renames .gitignore to .npmignore
# In order to prevent that, we remove the initial "."
# And the CLI then renames it
app
node_modules
build
dist
logs
capacitor.config.json
electron-plugins.js
Binary file added example/electron/assets/appIcon.ico
Binary file not shown.
Binary file added example/electron/assets/appIcon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions example/electron/electron-builder.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"appId": "com.yourdoamnin.yourapp",
"directories": {
"buildResources": "resources"
},
"files": ["assets/**/*", "build/**/*", "capacitor.config.*", "app/**/*"],
"publish": {
"provider": "github"
},
"nsis": {
"allowElevation": true,
"oneClick": false,
"allowToChangeInstallationDirectory": true
},
"win": {
"target": "nsis",
"icon": "assets/appIcon.ico"
},
"mac": {
"category": "your.app.category.type",
"target": "dmg"
}
}
75 changes: 75 additions & 0 deletions example/electron/live-runner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/no-var-requires */
const cp = require('child_process');
const chokidar = require('chokidar');
const electron = require('electron');

let child = null;
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const reloadWatcher = {
debouncer: null,
ready: false,
watcher: null,
restarting: false,
};

///*
function runBuild() {
return new Promise((resolve, _reject) => {
let tempChild = cp.spawn(npmCmd, ['run', 'build']);
tempChild.once('exit', () => {
resolve();
});
tempChild.stdout.pipe(process.stdout);
});
}
//*/

async function spawnElectron() {
if (child !== null) {
child.stdin.pause();
child.kill();
child = null;
await runBuild();
}
child = cp.spawn(electron, ['--inspect=5858', './']);
child.on('exit', () => {
if (!reloadWatcher.restarting) {
process.exit(0);
}
});
child.stdout.pipe(process.stdout);
}

function setupReloadWatcher() {
reloadWatcher.watcher = chokidar
.watch('./src/**/*', {
ignored: /[/\\]\./,
persistent: true,
})
.on('ready', () => {
reloadWatcher.ready = true;
})
.on('all', (_event, _path) => {
if (reloadWatcher.ready) {
clearTimeout(reloadWatcher.debouncer);
reloadWatcher.debouncer = setTimeout(async () => {
console.log('Restarting');
reloadWatcher.restarting = true;
await spawnElectron();
reloadWatcher.restarting = false;
reloadWatcher.ready = false;
clearTimeout(reloadWatcher.debouncer);
reloadWatcher.debouncer = null;
reloadWatcher.watcher = null;
setupReloadWatcher();
}, 500);
}
});
}

(async () => {
await runBuild();
await spawnElectron();
setupReloadWatcher();
})();
Loading