svelteesp32 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,17 +1,19 @@
1
1
  # `svelteesp32` ![image](https://badges.github.io/stability-badges/dist/stable.svg)
2
2
 
3
- # Convert Svelte (or React/Angular/Vue) JS application to serve it from ESP32 webserver
3
+ # Convert Svelte (or React/Angular/Vue) JS application to serve it from ESP32/ESP8266 webserver
4
4
 
5
5
  ### Forget SPIFFS and LittleFS now
6
6
 
7
- I often make small to medium-sized microcontroller solutions that run on ESP32. If a web interface is needed, I create a Svelte application. The Svelte application is practically served by the ESP32.
7
+ I often make small to medium-sized microcontroller solutions that run on ESP32 or ESP8266. If a web interface is needed, I create a Svelte application. The Svelte application is practically served by the ESP32/ESP8266.
8
8
 
9
9
  In order to be able to easily update OTA, it is important - from the users' point of view - that the update file **consists of one file**. I can't use the SPIFFS/LittleFS solution for this. It is necessary that the WebUI files are included inline in the Arduino or PlatformIO c++ code.
10
10
 
11
- This npm package provides a solution for **inserting any JS client application into the ESP32 web server** (PsychicHttp is my favorite, faster than ESPAsyncWebServer). For this, JS, html, css, font, assets, etc. files must be converted to binary byte array. Npm mode is easy to use and easy to **integrate into your CI/CD pipeline**.
11
+ This npm package provides a solution for **inserting any JS client application into the ESP web server** (PsychicHttp and also ESPAsyncWebServer available, PsychicHttp is the default). For this, JS, html, css, font, assets, etc. files must be converted to binary byte array. Npm mode is easy to use and easy to **integrate into your CI/CD pipeline**.
12
12
 
13
13
  > Starting with version v1.1.0, the ETag header is also supported.
14
14
 
15
+ > Starting with version v1.3.0, ESP8266/ESP8285 is also supported.
16
+
15
17
  ### Usage
16
18
 
17
19
  **Install package** as devDependency (it is practical if the package is part of the project so that you always receive updates)
@@ -23,10 +25,14 @@ npm install -D svelteesp32
23
25
  After a successful Svelte build (rollup/webpack/vite) **create an includeable c++ header** file
24
26
 
25
27
  ```bash
26
- npx svelteesp32 -s ../svelteapp/dist -o ../esp32project/svelteesp32.h --etag
28
+ // for PsychicHttpServer
29
+ npx svelteesp32 -e psychic -s ../svelteapp/dist -o ../esp32project/svelteesp32.h --etag
30
+
31
+ // for ESPAsyncWebServer
32
+ npx svelteesp32 -e async -s ../svelteapp/dist -o ../esp32project/svelteesp32.h --etag
27
33
  ```
28
34
 
29
- During the **translation process**, the processed file details are visible, and at the end, the result shows the ESP32's memory allocation (gzip size)
35
+ During the **translation process**, the processed file details are visible, and at the end, the result shows the ESP's memory allocation (gzip size)
30
36
 
31
37
  ```
32
38
  [assets/index-KwubEIf-.js]
@@ -70,6 +76,28 @@ void setup()
70
76
  }
71
77
  ```
72
78
 
79
+ or
80
+
81
+ ```c
82
+ ...
83
+
84
+ #include <ESPAsyncWebServer.h>
85
+ #include "svelteesp32.h"
86
+
87
+ AsyncWebServer server(80);
88
+
89
+ ...
90
+
91
+ void setup()
92
+ {
93
+ ...
94
+
95
+ initSvelteStaticFiles(&server);
96
+
97
+ server.begin();
98
+ }
99
+ ```
100
+
73
101
  The content of **generated file** (do not edit, just use)
74
102
 
75
103
  ```c
@@ -110,9 +138,15 @@ void initSvelteStaticFiles(PsychicHttpServer * server) {
110
138
  }
111
139
  ```
112
140
 
141
+ ### Engines and ESP variants
142
+
143
+ ESPAsyncWebServer is a popular web server that can be used on **both ESP32 and ESP8266 microcontrollers**. When you want to generate a file for this, use the `-e async` switch.
144
+
145
+ If you **only work on ESP32**, I recommend using PsychicHttpServer, which uses the native mode ESP-IDF web server inside. This way, its operation is significantly faster and more continuous. You can access this mode with the `-e psychic` switch.
146
+
113
147
  ### Gzip
114
148
 
115
- All modern browsers have been able to handle gzip-compressed content for years. For this reason, there is no question that the easily compressed JS and CSS files are stored compressed in the ESP32 and sent to the browser.
149
+ All modern browsers have been able to handle gzip-compressed content for years. For this reason, there is no question that the easily compressed JS and CSS files are stored compressed in the ESP32/ESP8266 and sent to the browser.
116
150
 
117
151
  During the translation process, data in gzip format is generated and will be used if the **size is greater than 100 bytes** and we experience a **reduction of at least 15%**. In such a case, the compressed data is unconditionally sent to the browser with the appropriate **Content-Encoding** header information.
118
152
 
@@ -122,32 +156,33 @@ Automatic compression can be turned off with the `--no-gzip` option.
122
156
 
123
157
  The ETag HTTP header can be used to significantly reduce network traffic. If the server sends ETag information, the client can check the integrity of the file by sending back this ETag (in `If-None-Match` header) without sending the data back again. All browsers use this function, the 304 HTTP response code is clearly visible in the network traffic.
124
158
 
125
- Since ESP32 data traffic is moderately expensive, it is an individual decision whether to use the ETag or not. We **recommend using ETag**, which adds a bit more code (about 1-3%) but results in a much cleaner operation.
159
+ Since microcontroller data traffic is moderately expensive, it is an individual decision whether to use the ETag or not. We **recommend using ETag**, which adds a bit more code (about 1-3%) but results in a much cleaner operation.
126
160
 
127
161
  The use of ETag is **not enabled by default**, this can be achieved with the `--etag` switch.
128
162
 
129
163
  ### Main entry point - index.html
130
164
 
131
- Typically, the entry point for web applications is the **index.htm or index.html** file. This does not need to be listed in the browser's address bar because web servers know that this file should be served by default. Svelteesp32 also does this: if there is an index.htm or index.html file, it sets it as the main file to be served. So using `http://esp32_xxx.local` or just entering the `http://x.y.w.z/` IP address will serve this main file.
165
+ Typically, the entry point for web applications is the **index.htm or index.html** file. This does not need to be listed in the browser's address bar because web servers know that this file should be served by default. Svelteesp32 also does this: if there is an index.htm or index.html file, it sets it as the main file to be served. So using `http://esp_xxx.local` or just entering the `http://x.y.w.z/` IP address will serve this main file.
132
166
 
133
167
  ### Command line options
134
168
 
135
- | Option | Required | Description | default |
136
- | ------------- | :------: | ---------------------------------------------- | ----------------------- |
137
- | `-s` | x | Source dist folder contains compiled web files | |
138
- | `-o` | x | Generated output file with path | `svelteesp32.h` |
139
- | `--etag` | | Use ETag header for cache | false |
140
- | `--no-gzip` | | Do not compress content with gzip | false -> gzip used |
141
- | `--espmethod` | x | Name of generated method | `initSvelteStaticFiles` |
142
- | `-h` | | Show help | |
169
+ | Option | Required | Description | default |
170
+ | ------------- | :------: | ---------------------------------------------------------------- | ----------------------- |
171
+ | `-e` | x | The engine for which the include file is created (psychic/async) | psychic |
172
+ | `-s` | x | Source dist folder contains compiled web files | |
173
+ | `-o` | x | Generated output file with path | `svelteesp32.h` |
174
+ | `--etag` | | Use ETag header for cache | false |
175
+ | `--no-gzip` | | Do not compress content with gzip | false -> gzip used |
176
+ | `--espmethod` | x | Name of generated method | `initSvelteStaticFiles` |
177
+ | `-h` | | Show help | |
143
178
 
144
179
  ### Q&A
145
180
 
146
181
  - **How big a frontend application can be placed?** If you compress the content with gzip, even a 3-4Mb assets directory can be placed. This is a serious enough amount to serve a complete application.
147
182
 
148
- - **How fast is cpp file compilation?** The cpp file can be large, but it can be compiled in a few seconds on any machine. If you don't modify your svelte/react app, it will use the already compiled cpp file (not recompile). This does not increase the speed of ESP32 development.
183
+ - **How fast is cpp file compilation?** The cpp file can be large, but it can be compiled in a few seconds on any machine. If you don't modify your svelte/react app, it will use the already compiled cpp file (not recompile). This does not increase the speed of ESP32/ESP8266 development.
149
184
 
150
- - **Does the solution use PROGMEM?** No and yes. ESP32 no longer has PROGMEM. (Exists, but does not affect the translation). Instead, if we use a const array in the global namespace, its content will be placed in the code area, i.e. it will not be used from the heap or the stack, so the content of the files to be served will be placed next to the code.
185
+ - **Does the solution use PROGMEM?** No and yes. ESP32 no longer has PROGMEM. (Exists, but does not affect the translation). Instead, if we use a const array in the global namespace, its content will be placed in the code area, i.e. it will not be used from the heap or the stack, so the content of the files to be served will be placed next to the code. When working on ESP8266, PROGMEM will actually be used.
151
186
 
152
187
  - **Is this safe to use in production?** I suggest you give it a try! If you find it useful and safe in several different situations, feel free to use it, just like any other free library.
153
188
 
@@ -1,4 +1,5 @@
1
1
  interface ICopyFilesArguments {
2
+ engine: 'psychic' | 'async';
2
3
  sourcepath: string;
3
4
  outputfile: string;
4
5
  espmethod: string;
@@ -4,6 +4,18 @@ exports.cmdLine = void 0;
4
4
  const node_fs_1 = require("node:fs");
5
5
  const ts_command_line_args_1 = require("ts-command-line-args");
6
6
  exports.cmdLine = (0, ts_command_line_args_1.parse)({
7
+ engine: {
8
+ type: (value) => {
9
+ if (value === 'psychic')
10
+ return 'psychic';
11
+ if (value === 'async')
12
+ return 'async';
13
+ throw new Error(`Invalid engine: ${value}`);
14
+ },
15
+ alias: 'e',
16
+ description: 'The engine for which the include file is created',
17
+ defaultValue: 'psychic'
18
+ },
7
19
  sourcepath: {
8
20
  type: String,
9
21
  alias: 's',
@@ -39,3 +51,4 @@ if (!(0, node_fs_1.existsSync)(exports.cmdLine.sourcepath) || !(0, node_fs_1.sta
39
51
  console.error(`Directory ${exports.cmdLine.sourcepath} not exists or not a directory`);
40
52
  process.exit(1);
41
53
  }
54
+ console.log(`[SvelteESP32] Generate code for ${exports.cmdLine.engine} engine`);
package/dist/cppCode.js CHANGED
@@ -1,70 +1,99 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCppCode = void 0;
4
+ const handlebars_1 = require("handlebars");
4
5
  const commandLine_1 = require("./commandLine");
5
- const replaceAll = (s, from, to) => {
6
- while (s.includes(from))
7
- s = s.replace(from, to);
8
- return s;
9
- };
10
- const blockTemplateETag = `if (request->hasHeader("If-None-Match") && request->header("If-None-Match") == String(etag$index$)) {
6
+ const psychicTemplate = `
7
+ //engine: PsychicHttpServer
8
+ //cmdline: {{commandLine}}
9
+ //created: {{now}}
10
+ //files: {{fileCount}}
11
+ //memory: {{fileSize}}
12
+
13
+ {{#each sources}}
14
+ const uint8_t data{{this.index}}[{{this.length}}] = { {{this.bytes}} };
15
+ {{#if ../isEtag}}
16
+ const char * etag{{this.index}} = "{{this.md5}}";
17
+ {{/if}}
18
+ {{/each}}
19
+
20
+ void {{methodName}}(PsychicHttpServer * server) {
21
+ {{#each sources}}
22
+
23
+ {{#if this.isDefault}}server->defaultEndpoint = {{/if}}server->on("/{{this.filename}}", HTTP_GET, [](PsychicRequest * request)
24
+ {
25
+ {{#if ../isEtag}}
26
+ if (request->hasHeader("If-None-Match") && request->header("If-None-Match") == String(etag{{this.index}})) {
11
27
  PsychicResponse response304(request);
12
28
  response304.setCode(304);
13
29
  return response304.send();
14
30
  }
15
- `;
16
- const blockTemplate = `
17
- $default$server->on("/$filename$", HTTP_GET, [](PsychicRequest * request)
18
- {
19
- ${commandLine_1.cmdLine.etag ? blockTemplateETag : ''}
31
+ {{/if}}
20
32
  PsychicResponse response(request);
21
- response.setContentType("$mime$");
22
- response.addHeader("Content-Encoding", "$encoding$");
23
- ${commandLine_1.cmdLine.etag ? `response.addHeader("ETag", etag$index$);` : ''}
24
- response.setContent(data$index$, sizeof(data$index$));
33
+ response.setContentType("{{this.mime}}");
34
+ {{#if this.isGzip}}
35
+ response.addHeader("Content-Encoding", "gzip");
36
+ {{/if}}
37
+ {{#if ../isEtag}}
38
+ response.addHeader("ETag", etag{{this.index}});
39
+ {{/if}}
40
+ response.setContent(data{{this.index}}, sizeof(data{{this.index}}));
25
41
  return response.send();
26
42
  });
27
- `;
28
- const getCppBlock = (source) => {
29
- let result = blockTemplate;
30
- result = replaceAll(result, '$default$', source.filename.startsWith('index.htm') ? 'server->defaultEndpoint = ' : '');
31
- result = replaceAll(result, '$index$', source.index.toString());
32
- result = replaceAll(result, '$filename$', source.filename);
33
- result = replaceAll(result, '$size$', source.content.length.toString());
34
- result = replaceAll(result, '$mime$', source.mime);
35
- result = replaceAll(result, '$encoding$', source.isGzip ? 'gzip' : 'identity');
36
- return result;
37
- };
38
- const fileTemplate = `//cmdline: $commandline$
39
- //created: $now$
40
- //files: $filecount$
41
- //memory: $filesize$
43
+ {{/each}}
44
+ }`;
45
+ const asyncTemplate = `
46
+ //engine: ESPAsyncWebServer
47
+ //cmdline: {{commandLine}}
48
+ //created: {{now}}
49
+ //files: {{fileCount}}
50
+ //memory: {{fileSize}}
42
51
 
43
- $filedataarrays$
44
- $hashaarrays$
52
+ {{#each sources}}
53
+ const uint8_t data{{this.index}}[{{this.length}}] PROGMEM = { {{this.bytes}} };
54
+ {{#if ../isEtag}}
55
+ const char * etag{{this.index}} = "{{this.md5}}";
56
+ {{/if}}
57
+ {{/each}}
45
58
 
46
- void $method$(PsychicHttpServer * server) {
47
- $code$
48
- }`;
49
- const getCppCode = (sources) => {
50
- const fileDataArrays = [];
51
- const hashArrays = [];
52
- const blocks = [];
53
- for (const source of sources) {
54
- const bytesString = [...source.content].map((v) => `0x${v.toString(16)}`).join(', ');
55
- fileDataArrays.push(`const uint8_t data${source.index}[${source.content.length}] = {${bytesString}};`);
56
- hashArrays.push(`const char * etag${source.index} = "${source.md5}";`);
57
- blocks.push(getCppBlock(source));
59
+ void {{methodName}}(AsyncWebServer * server) {
60
+ {{#each sources}}
61
+
62
+ ArRequestHandlerFunction func{{this.index}} = [](AsyncWebServerRequest * request)
63
+ {
64
+ {{#if ../isEtag}}
65
+ if (request->hasHeader("If-None-Match") && request->getHeader("If-None-Match")->value() == String(etag{{this.index}})) {
66
+ request->send(304);
67
+ return;
58
68
  }
59
- let result = fileTemplate;
60
- result = replaceAll(result, '$commandline$', process.argv.slice(2).join(' '));
61
- result = replaceAll(result, '$now$', `${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`);
62
- result = replaceAll(result, '$filecount$', sources.length.toString());
63
- result = replaceAll(result, '$filesize$', sources.reduce((previous, current) => previous + current.content.length, 0).toString());
64
- result = replaceAll(result, '$filedataarrays$', fileDataArrays.join('\n'));
65
- result = replaceAll(result, '$hashaarrays$', commandLine_1.cmdLine.etag ? hashArrays.join('\n') : '');
66
- result = replaceAll(result, '$method$', commandLine_1.cmdLine.espmethod);
67
- result = replaceAll(result, '$code$', blocks.join(''));
68
- return result;
69
- };
69
+ {{/if}}
70
+ AsyncWebServerResponse *response = request->beginResponse_P(200, "{{this.mime}}", data{{this.index}}, {{this.length}});
71
+ {{#if this.isGzip}}
72
+ response->addHeader("Content-Encoding", "gzip");
73
+ {{/if}}
74
+ {{#if ../isEtag}}
75
+ response->addHeader("ETag", etag{{this.index}});
76
+ {{/if}}
77
+ request->send(response);
78
+ };
79
+ server->on("/{{this.filename}}", HTTP_GET, func{{this.index}});
80
+ {{#if this.isDefault}}
81
+ server->on("/", HTTP_GET, func{{this.index}});
82
+ {{/if}}
83
+ {{/each}}
84
+ }`;
85
+ const getCppCode = (sources) => (0, handlebars_1.compile)(commandLine_1.cmdLine.engine === 'psychic' ? psychicTemplate : asyncTemplate)({
86
+ commandLine: process.argv.slice(2).join(' '),
87
+ now: `${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,
88
+ fileCount: sources.length.toString(),
89
+ fileSize: sources.reduce((previous, current) => previous + current.content.length, 0).toString(),
90
+ sources: sources.map((s) => ({
91
+ ...s,
92
+ length: s.content.length,
93
+ bytes: [...s.content].map((v) => `0x${v.toString(16)}`).join(', '),
94
+ isDefault: s.filename.startsWith('index.htm')
95
+ })),
96
+ isEtag: commandLine_1.cmdLine.etag,
97
+ methodName: commandLine_1.cmdLine.espmethod
98
+ }).trim();
70
99
  exports.getCppCode = getCppCode;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelteesp32",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Convert Svelte (or any frontend) JS application to serve it from ESP32 webserver (PsychicHttp)",
5
5
  "author": "BCsabaEngine",
6
6
  "license": "ISC",
@@ -28,8 +28,10 @@
28
28
  },
29
29
  "homepage": "https://github.com/BCsabaEngine/svelteesp32",
30
30
  "scripts": {
31
- "dev": "nodemon src/index.ts -- -s ./svelte/dist -o ../../../Arduino/EspSvelte/svelteesp32.h --etag",
32
- "dev:local": "nodemon src/index.ts -- -s ./svelte/dist -o ./svelteesp32.h --etag",
31
+ "dev:psychic": "nodemon src/index.ts -- -e psychic -s ./svelte/dist -o ../../../Arduino/SvelteEsp32/svelteesp32.h --etag",
32
+ "dev:psychic:local": "nodemon src/index.ts -- -e psychic -s ./svelte/dist -o ./svelteesp32.h --etag",
33
+ "dev:async": "nodemon src/index.ts -- -e async -s ./svelte/dist -o ../../../Arduino/SvelteEsp8266/svelteesp32.h --etag",
34
+ "dev:async:local": "nodemon src/index.ts -- -e async -s ./svelte/dist -o ./svelteesp32.h --etag",
33
35
  "clean": "tsc --build --clean",
34
36
  "build": "tsc --build --clean && tsc --build --force",
35
37
  "format:check": "prettier --check .",
@@ -41,16 +43,21 @@
41
43
  "npm-publish-minor": "npm run build && npm version minor && npm publish && npm run clean && git push"
42
44
  },
43
45
  "keywords": [
44
- "Svelte",
46
+ "svelte",
47
+ "angular",
48
+ "react",
49
+ "vue",
45
50
  "eps32",
51
+ "esp8266",
46
52
  "webserver",
47
- "PsychicHttp"
53
+ "psychichttpserver",
54
+ "espasyncwebserver"
48
55
  ],
49
56
  "devDependencies": {
50
57
  "@types/mime-types": "^2.1.4",
51
58
  "@types/node": "^20.11.19",
52
- "@typescript-eslint/eslint-plugin": "^7.0.1",
53
- "@typescript-eslint/parser": "^7.0.1",
59
+ "@typescript-eslint/eslint-plugin": "^7.0.2",
60
+ "@typescript-eslint/parser": "^7.0.2",
54
61
  "eslint": "^8.56.0",
55
62
  "eslint-config-prettier": "^9.1.0",
56
63
  "eslint-plugin-simple-import-sort": "^12.0.0",
@@ -63,6 +70,7 @@
63
70
  },
64
71
  "dependencies": {
65
72
  "glob": "^10.3.10",
73
+ "handlebars": "^4.7.8",
66
74
  "mime-types": "^2.1.35",
67
75
  "ts-command-line-args": "^2.5.1"
68
76
  }