@enbox/create-dapp 0.0.0-stage → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Liran Cohen
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,46 @@
1
- # Temporary Holding Version
1
+ # @enbox/create-dapp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Create a minimal Enbox React app with a wallet connection, a profile card,
4
+ and a removable private-data demo.
5
+
6
+ Requires Node.js 22.12.0 or newer. Create an app with either command:
7
+
8
+ ```sh
9
+ npm create @enbox/dapp@latest my-app
10
+ # or
11
+ bun create @enbox/dapp@latest my-app
12
+ ```
13
+
14
+ Then run:
15
+
16
+ ```sh
17
+ cd my-app
18
+ npm install
19
+ npm run dev
20
+ ```
21
+
22
+ The CLI detects npm or Bun from the invoking package manager and prints its
23
+ commands. Use `--package-manager npm` or `--package-manager bun` to override
24
+ that choice. The template includes no lockfile: your first install creates one
25
+ for your package manager. Commit it and use frozen installs thereafter.
26
+
27
+ The generator copies its bundled template into a new or empty directory. It
28
+ does not install packages, run Git, or make network requests. It refuses
29
+ nonempty destinations and symbolic-link targets; there is no force option.
30
+ Use `.` for an empty current directory. Omitting the directory prompts in an
31
+ interactive terminal; scripts must provide it explicitly.
32
+
33
+ The directory's basename becomes the display name in `src/app.json`. Its
34
+ normalized lowercase npm name becomes both the package name and the stable
35
+ `app.json` ID. The ID identifies
36
+ the app to the wallet and defines its private demo protocol namespace. Keep
37
+ the ID when changing the display name so saved data remains in the same
38
+ namespace. Source code is copied unchanged. Run `--help` for usage or
39
+ `--version` for the generator version.
40
+
41
+ From this repository, run the CLI and its tests without publishing:
42
+
43
+ ```sh
44
+ node packages/create-dapp/bin/create-dapp.mjs /tmp/my-enbox-app
45
+ node --test packages/create-dapp/tests/*.test.mjs
46
+ ```
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { parseArgs } from 'node:util';
8
+
9
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));
10
+ const manifest = JSON.parse(fs.readFileSync(join(packageRoot, 'package.json'), 'utf8'));
11
+ const excluded = new Set([
12
+ 'node_modules', 'dist', 'build', '.git', '.artifacts', '.vite', '.cache',
13
+ 'coverage', 'test-results', 'playwright-report', '.DS_Store',
14
+ 'package-lock.json', 'bun.lock', 'bun.lockb', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml',
15
+ ]);
16
+
17
+ const usage = `Create a minimal Enbox React application.
18
+
19
+ Usage:
20
+ npm create @enbox/dapp@latest [directory]
21
+ bun create @enbox/dapp@latest [directory]
22
+ npx @enbox/create-dapp@latest [directory]
23
+
24
+ Options:
25
+ -h, --help Show this help
26
+ -v, --version Show the generator version
27
+ --package-manager <npm|bun> Override the invoking package manager
28
+
29
+ The destination must be empty. No dependencies are installed and no Git
30
+ repository is created. Use "." to create an app in the current empty directory.
31
+ `;
32
+
33
+ function assertEmptyDestination(destination) {
34
+ const stat = fs.lstatSync(destination, { throwIfNoEntry: false });
35
+ if (stat === undefined) return;
36
+ if (stat.isSymbolicLink()) throw new Error('The destination must not be a symbolic link.');
37
+ if (!stat.isDirectory()) throw new Error('The destination must be a directory.');
38
+ if (fs.readdirSync(destination).length !== 0) throw new Error('The destination directory is not empty.');
39
+ }
40
+
41
+ function readTemplate(directory, prefix = '', files = new Map()) {
42
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
43
+ if (excluded.has(entry.name) || entry.name.endsWith('.tsbuildinfo')) continue;
44
+ const source = join(directory, entry.name);
45
+ const name = prefix === '' && entry.name === '_gitignore' ? '.gitignore' : entry.name;
46
+ const relative = join(prefix, name);
47
+ if (entry.isDirectory()) readTemplate(source, relative, files);
48
+ else if (entry.isFile()) {
49
+ if (files.has(relative)) throw new Error(`Duplicate template file: ${relative}`);
50
+ files.set(relative, fs.readFileSync(source));
51
+ } else throw new Error(`Unsupported template entry: ${relative}`);
52
+ }
53
+ return files;
54
+ }
55
+
56
+ function customizeJson(files, path, update) {
57
+ try {
58
+ const contents = files.get(path);
59
+ if (contents === undefined) throw new Error('file is missing');
60
+ const value = JSON.parse(contents.toString('utf8'));
61
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('expected a JSON object');
62
+ update(value);
63
+ files.set(path, Buffer.from(`${JSON.stringify(value, null, 2)}\n`));
64
+ } catch (cause) {
65
+ throw new Error(`Invalid starter template ${path}: ${cause.message}`, { cause });
66
+ }
67
+ }
68
+
69
+ function packageName(name) {
70
+ return name.normalize('NFKD').toLowerCase().replace(/[\u0300-\u036f]/g, '')
71
+ .replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 214).replace(/-+$/g, '') || 'enbox-dapp';
72
+ }
73
+
74
+ function createProject(destination) {
75
+ assertEmptyDestination(destination);
76
+ const files = readTemplate(join(packageRoot, 'template'));
77
+ const displayName = basename(destination);
78
+ const name = packageName(displayName);
79
+ customizeJson(files, 'package.json', (value) => { value.name = name; });
80
+ customizeJson(files, join('src', 'app.json'), (value) => {
81
+ value.id = name;
82
+ value.name = displayName;
83
+ });
84
+
85
+ const createdFiles = [];
86
+ const createdDirectories = [];
87
+ const ensureDirectory = (directory) => {
88
+ try {
89
+ fs.mkdirSync(directory);
90
+ createdDirectories.push(directory);
91
+ } catch (cause) {
92
+ if (cause.code === 'ENOENT') {
93
+ ensureDirectory(dirname(directory));
94
+ ensureDirectory(directory);
95
+ } else if (cause.code !== 'EEXIST' || !fs.lstatSync(directory).isDirectory()) throw cause;
96
+ }
97
+ };
98
+ try {
99
+ ensureDirectory(destination);
100
+ assertEmptyDestination(destination);
101
+ for (const [relative, contents] of files) {
102
+ const target = join(destination, relative);
103
+ ensureDirectory(dirname(target));
104
+ const descriptor = fs.openSync(target, 'wx');
105
+ createdFiles.push(target);
106
+ try { fs.writeFileSync(descriptor, contents); }
107
+ finally { fs.closeSync(descriptor); }
108
+ }
109
+ } catch (cause) {
110
+ // Remove only entries created by this invocation; keep preexisting directories.
111
+ for (const file of createdFiles.reverse()) {
112
+ try { fs.unlinkSync(file); } catch {}
113
+ }
114
+ for (const directory of createdDirectories.reverse()) {
115
+ try { fs.rmdirSync(directory); } catch {}
116
+ }
117
+ throw new Error(`Could not create the app: ${cause.message}`, { cause });
118
+ }
119
+ }
120
+
121
+ function quoteDirectory(directory) {
122
+ return process.platform === 'win32'
123
+ ? `'${directory.replaceAll("'", "''")}'`
124
+ : `'${directory.replaceAll("'", "'\\''")}'`;
125
+ }
126
+
127
+ async function main() {
128
+ const { values, positionals } = parseArgs({
129
+ options: {
130
+ help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
131
+ 'package-manager': { type: 'string' },
132
+ },
133
+ allowPositionals: true,
134
+ });
135
+ if (values.help) { console.log(usage); return; }
136
+ if (values.version) { console.log(manifest.version); return; }
137
+ const manager = values['package-manager'] ?? (process.env.npm_config_user_agent?.startsWith('bun/') ? 'bun' : 'npm');
138
+ if (manager !== 'npm' && manager !== 'bun') throw new Error('The package manager must be npm or bun.');
139
+ if (positionals.length > 1) throw new Error('Provide one target directory. Run with --help for usage.');
140
+ let directory = positionals[0];
141
+ if (directory === undefined) {
142
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
143
+ throw new Error('Provide a target directory. Run with --help for usage.');
144
+ }
145
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
146
+ try { directory = await prompt.question('Project directory: '); }
147
+ finally { prompt.close(); }
148
+ }
149
+ if (directory.trim() === '' || /[\u0000-\u001f\u007f]/.test(directory)) {
150
+ throw new Error('Provide a nonempty target directory without control characters.');
151
+ }
152
+ const destination = resolve(directory);
153
+ createProject(destination);
154
+ const changeDirectory = process.platform === 'win32' ? 'Set-Location -LiteralPath' : 'cd';
155
+ console.log(`Created ${basename(destination)}.\n\n${process.platform === 'win32' ? 'In PowerShell' : 'Next'}:\n ${changeDirectory} ${quoteDirectory(destination)}\n ${manager} install\n ${manager} run dev`);
156
+ }
157
+
158
+ main().catch((cause) => {
159
+ console.error(`create-dapp: ${cause.message}`);
160
+ process.exitCode = 1;
161
+ });
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@enbox/create-dapp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Create a minimal Enbox React application",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/enboxorg/enbox-react.git",
10
+ "directory": "packages/create-dapp"
11
+ },
12
+ "bin": {
13
+ "create-dapp": "bin/create-dapp.mjs"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "template/src",
18
+ "template/index.html",
19
+ "template/package.json",
20
+ "template/tsconfig.json",
21
+ "template/vite.config.ts",
22
+ "template/README.md",
23
+ "template/_gitignore",
24
+ "template/.npmrc",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "engines": {
29
+ "node": ">=22.12.0"
30
+ },
31
+ "scripts": {
32
+ "test": "node --test tests/*.test.mjs"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "tag": "latest"
37
+ }
38
+ }
@@ -0,0 +1,79 @@
1
+ # Hello, Enbox
2
+
3
+ A small React app with a wallet connection, a read-only public profile, and
4
+ a private task board with projects and tasks. No application server is required.
5
+
6
+ ## Run it
7
+
8
+ Use Node 22.12 or newer:
9
+
10
+ ```sh
11
+ npm install
12
+ npm run dev
13
+ ```
14
+
15
+ Open the local URL and choose **Connect wallet**. Enbox handles wallet selection
16
+ and approval. Create a project, add tasks, and check them off as you finish.
17
+ Select a task to edit its title or delete it. Completed tasks can be reopened.
18
+ Switching projects selects that project’s own tasks. Saved values come from native
19
+ live record views and are restored when this profile returns.
20
+
21
+ ```sh
22
+ npm run typecheck
23
+ npm run build
24
+ npm run preview
25
+ ```
26
+
27
+ The app owns its service worker. Startup waits until that worker controls the
28
+ page before initializing Enbox. Vite bundles the worker without a separate PWA
29
+ toolchain. Production builds precache the app shell for
30
+ later offline visits; `npm run preview` serves that built app locally. Deploy
31
+ the generated `dist` directory on an HTTPS origin with service worker support.
32
+
33
+ You can also use `bun install` and `bun run dev`. No lockfile is generated
34
+ until your first install. Commit the resulting `package-lock.json` or `bun.lock`;
35
+ then use `npm ci` or `bun install --frozen-lockfile` in CI. Direct dependencies
36
+ use exact versions. Update the manifest and your lockfile together when
37
+ accepting dependency or security fixes.
38
+
39
+ ## Make it yours
40
+
41
+ `src/app.json` contains the display name used in the page, browser title, and
42
+ wallet approval screen, plus a stable app ID. Changing the display name leaves
43
+ the app ID and demo data namespace intact. `src/application.ts` defines the application manifest
44
+ and wallet configuration. `src/main.tsx` mounts the SDK provider; `src/App.tsx`
45
+ contains the app shell without owning authentication state.
46
+
47
+ The profile card reads published profile information through `useProfile`.
48
+ Names, images, settlement state, and image URL lifetimes belong to the SDK.
49
+ Missing profiles and unavailable images have local display fallbacks.
50
+ The wallet's profile label is used when a public display name is unavailable;
51
+ the expanded details still show which name is publicly published.
52
+
53
+ The removable demo lives entirely in `src/demo`:
54
+
55
+ - `protocol.ts` declares encrypted `project` and `project/task` records with
56
+ payload validators. Tasks store a title and completion state.
57
+ - `use-task-board.ts` defines `useProjects`, `useTasks`, and `useTask` with
58
+ `useEnboxRecords` and `useEnboxRecord`. A child selection takes its direct
59
+ parent context ID; task details also select an exact record ID.
60
+ - `TaskBoard.tsx` renders the board and calls typed create, patch, and delete commands.
61
+ Simple event handlers use `mutate`. Forms await `mutateAsync` and check
62
+ `isCurrent()` before clearing drafts or closing details. Native observation updates the displayed data.
63
+ - `demo.css` styles the demo. Shared app and profile styles live in `src/style.css`.
64
+
65
+ To replace the demo, register your own typed application protocol in
66
+ `application.ts` in place of `TaskBoardProtocol`. Then delete `src/demo` and remove
67
+ the `TaskBoard` import and component from `App.tsx`. Enbox requires at least one
68
+ application protocol, so keep your replacement registered. The profile card,
69
+ connection shell, and service worker remain the base for your app.
70
+
71
+ The demo's default protocol URI is
72
+ `https://example.com/<encoded app ID>/demo/v2`. Replace the URI expression in
73
+ `src/demo/protocol.ts` with a stable URI
74
+ you control before publishing. This URI identifies saved records and wallet
75
+ grants: changing it creates a different data namespace. Once deployed, keep
76
+ that identifier fixed when changing the app's display name.
77
+
78
+ Public profile information and the encrypted task board are separate. Task
79
+ updates change this app’s private records; they do not edit the public profile.
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ *.local
4
+ *.tsbuildinfo
5
+ .env
6
+ .env.*
7
+ !.env.example
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <meta name="theme-color" content="#f6f8fb" />
7
+ <meta name="description" content="Your identity, your data, your first Enbox dapp." />
8
+ <title>Hello, Enbox</title>
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ <script type="module" src="/src/main.tsx"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "enbox-dapp",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "typecheck": "tsc --noEmit",
9
+ "build": "tsc --noEmit && vite build",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "@enbox/browser": "0.3.82",
14
+ "@enbox/react": "0.0.7",
15
+ "react": "19.3.0",
16
+ "react-dom": "19.3.0"
17
+ },
18
+ "devDependencies": {
19
+ "@types/node": "22.19.15",
20
+ "@types/react": "19.3.0",
21
+ "@types/react-dom": "19.2.3",
22
+ "@vitejs/plugin-react": "5.2.0",
23
+ "typescript": "5.9.3",
24
+ "vite": "6.4.4"
25
+ },
26
+ "engines": {
27
+ "node": ">=22.12.0"
28
+ }
29
+ }
@@ -0,0 +1,75 @@
1
+ import { useEnboxConnection } from '@enbox/react';
2
+ import { useEffect } from 'react';
3
+
4
+ import app from './app.json' with { type: 'json' };
5
+ import { TaskBoard } from './demo/TaskBoard.js';
6
+ import { ProfileCard } from './ProfileCard.js';
7
+
8
+ export function App() {
9
+ const connection = useEnboxConnection();
10
+ const busy = connection.isConnecting || connection.isDisconnecting;
11
+ useEffect(() => { document.title = app.name; }, []);
12
+
13
+ return (
14
+ <div className="app-shell">
15
+ <header className="app-header">
16
+ <a className="wordmark" href="./" aria-label={`${app.name} home`}>
17
+ <span className="brand-symbol" aria-hidden="true">e</span>
18
+ <span>Made with Enbox</span>
19
+ </a>
20
+ {connection.isConnected && (
21
+ <button className="button button-quiet" type="button" disabled={busy}
22
+ onClick={() => { void connection.disconnect().catch(() => {}); }}>
23
+ {connection.isDisconnecting ? 'Disconnecting…' : 'Disconnect'}
24
+ </button>
25
+ )}
26
+ </header>
27
+
28
+ <main>
29
+ <div className="intro">
30
+ <p className="eyebrow">A small beginning</p>
31
+ <h1>{app.name}</h1>
32
+ <p>Bring your profile. Make a little space your own.</p>
33
+ </div>
34
+
35
+ {connection.walletRepair && (
36
+ <div className="notice" role="status">
37
+ <div>
38
+ <strong>Reconnect your profile</strong>
39
+ <p>Your wallet access needs a refresh before you can save.</p>
40
+ </div>
41
+ <button className="button button-secondary" type="button" disabled={busy}
42
+ onClick={() => { void connection.connect().catch(() => {}); }}>
43
+ {connection.isConnecting ? 'Reconnecting…' : 'Reconnect'}
44
+ </button>
45
+ </div>
46
+ )}
47
+ {connection.connectionError && (
48
+ <div className="notice notice-error" role="alert">
49
+ <p>{connection.connectionError.message}</p>
50
+ </div>
51
+ )}
52
+
53
+ {connection.isConnected && connection.did ? (
54
+ <div className="connected-content">
55
+ <ProfileCard enbox={connection.enbox} did={connection.did} identityName={connection.identityName} />
56
+ <TaskBoard disabled={busy || connection.walletRepair !== undefined} />
57
+ </div>
58
+ ) : (
59
+ <section className="panel connect-panel" aria-labelledby="connect-title">
60
+ <div className="welcome-symbol" aria-hidden="true">✳</div>
61
+ <h2 id="connect-title">A hello that belongs to you.</h2>
62
+ <p>Connect your profile to make this space your own.</p>
63
+ <button className="button button-primary" type="button" disabled={busy}
64
+ onClick={() => { void connection.connect().catch(() => {}); }}>
65
+ {connection.isConnecting ? 'Connecting…' : connection.isDisconnecting ? 'Disconnecting…' : 'Connect wallet'}
66
+ {!busy && <span aria-hidden="true">↗</span>}
67
+ </button>
68
+ <p className="connect-caption">Your wallet will ask you to approve access.</p>
69
+ </section>
70
+ )}
71
+ </main>
72
+ <footer className="app-footer">Your identity. Your data. Your little corner of the web.</footer>
73
+ </div>
74
+ );
75
+ }
@@ -0,0 +1,54 @@
1
+ import type { Enbox } from '@enbox/browser';
2
+ import { useProfile } from '@enbox/react';
3
+ import { useState } from 'react';
4
+
5
+ export function ProfileCard({ enbox, did, identityName }: {
6
+ enbox: Enbox | undefined;
7
+ did: string;
8
+ identityName?: string | undefined;
9
+ }) {
10
+ const profile = useProfile(enbox, did);
11
+ const [failedAvatar, setFailedAvatar] = useState<string>();
12
+ const publishedName = profile.displayName?.trim();
13
+ const name = publishedName || identityName?.trim();
14
+ const avatar = profile.avatarUrl !== failedAvatar ? profile.avatarUrl : undefined;
15
+ const initials = name?.split(/\s+/).slice(0, 2).map((part) => part[0]).join('').toUpperCase();
16
+ const profileStatus = profile.fields.profile.status;
17
+ const publicName = publishedName || (profileStatus === 'idle' || profileStatus === 'loading' ? 'Loading…'
18
+ : profileStatus === 'error' ? 'Unavailable' : 'Not published');
19
+ const shortDid = did.length > 34 ? `${did.slice(0, 22)}…${did.slice(-8)}` : did;
20
+
21
+ return (
22
+ <section className="panel profile-card" aria-labelledby="profile-title">
23
+ <div className="profile-heading">
24
+ <div className="avatar" aria-hidden="true">
25
+ {avatar
26
+ ? <img src={avatar} alt="" onError={() => setFailedAvatar(avatar)} />
27
+ : <span>{initials || '◌'}</span>}
28
+ </div>
29
+ <div className="profile-identity">
30
+ <p className="eyebrow">Your public profile</p>
31
+ <h2 id="profile-title">{name || 'Your profile'}</h2>
32
+ <p className="short-did" title={did}>{shortDid}</p>
33
+ </div>
34
+ <span className="connected-badge"><span aria-hidden="true" />Connected</span>
35
+ </div>
36
+ {profileStatus === 'loading' && !name && <p role="status">Looking up your public profile…</p>}
37
+ {profileStatus === 'not-found' && <p>No public profile yet. You can still make yourself at home.</p>}
38
+ {profileStatus === 'error' && (
39
+ <p className="profile-message" role="status">Your public profile couldn’t be loaded. The app is still yours to use.</p>
40
+ )}
41
+ <details className="profile-details">
42
+ <summary>Profile details</summary>
43
+ {profile.bio && <p className="profile-bio">{profile.bio}</p>}
44
+ <dl>
45
+ <dt>Profile ID</dt><dd><code>{did}</code></dd>
46
+ <dt>Public name</dt><dd>{publicName}</dd>
47
+ {profile.location && <><dt>Location</dt><dd>{profile.location}</dd></>}
48
+ {profile.website && <><dt>Website</dt><dd>{profile.website}</dd></>}
49
+ </dl>
50
+ {profile.fields.profile.failure && <p className="error-detail">{profile.fields.profile.failure.message}</p>}
51
+ </details>
52
+ </section>
53
+ );
54
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "id": "enbox-dapp",
3
+ "name": "Hello, Enbox"
4
+ }
@@ -0,0 +1,10 @@
1
+ import { defineApplicationManifest } from '@enbox/react/config';
2
+ import type { CreateEnboxClientOptions } from '@enbox/react/config';
3
+
4
+ import app from './app.json' with { type: 'json' };
5
+ import { TaskBoardProtocol } from './demo/protocol.js';
6
+
7
+ export const config = {
8
+ application: defineApplicationManifest({ protocols: [TaskBoardProtocol] }),
9
+ wallet: { appName: app.name, applicationId: app.id },
10
+ } satisfies CreateEnboxClientOptions;
@@ -0,0 +1,136 @@
1
+ import { useState } from 'react';
2
+ import type { FormEvent } from 'react';
3
+
4
+ import { useProjects, useTask, useTasks } from './use-task-board.js';
5
+ import './demo.css';
6
+
7
+ export function TaskBoard({ disabled = false }: { disabled?: boolean }) {
8
+ const projects = useProjects();
9
+ const [projectContextId, setProjectContextId] = useState<string>();
10
+ const [name, setName] = useState('');
11
+ const prompt = projects.isLoading ? 'Loading projects…'
12
+ : projects.isReady && projects.records.length === 0 ? 'Create your first project to get started.'
13
+ : 'Select a project to see its tasks.';
14
+ async function addProject(event: FormEvent) {
15
+ event.preventDefault();
16
+ try {
17
+ const record = await projects.create.mutateAsync({ name: name.trim() });
18
+ if (projects.create.isCurrent()) { setProjectContextId(record.contextId); setName(''); }
19
+ } catch { /* The mutation error is rendered below. */ }
20
+ }
21
+ return (
22
+ <section className="panel demo" aria-labelledby="demo-title">
23
+ <h2 id="demo-title">Your projects</h2>
24
+ <p>A private task board. Create a project, add tasks, and make a little progress.</p>
25
+ <form className="demo-form" onSubmit={addProject}>
26
+ <label htmlFor="project-name">Project name</label>
27
+ <input id="project-name" value={name} maxLength={60} required
28
+ disabled={disabled || projects.create.isPending} onChange={(event) => setName(event.target.value)} />
29
+ <button className="button button-secondary" disabled={disabled || projects.create.isPending || !name.trim()}>
30
+ {projects.create.isPending ? 'Creating…' : 'Create project'}
31
+ </button>
32
+ </form>
33
+ {projects.create.error && <p role="alert">Couldn’t create the project: {projects.create.error.message}</p>}
34
+ {projects.status === 'error' && <div role="alert">
35
+ <p>Couldn’t load projects: {projects.error.message}</p>
36
+ <button type="button" disabled={disabled} onClick={() => projects.retry()}>Try again</button>
37
+ </div>}
38
+ <div className="project-picker" role="group" aria-label="Projects">
39
+ {projects.records.map((project) => <button type="button" className="button button-quiet" key={project.id} disabled={disabled}
40
+ aria-pressed={project.contextId === projectContextId} onClick={() => setProjectContextId(project.contextId)}>{project.data.name}</button>)}
41
+ </div>
42
+ {projects.hasMore && <button type="button" disabled={disabled || projects.isLoadingMore}
43
+ onClick={() => projects.loadMore()}>More projects</button>}
44
+ {projectContextId !== undefined
45
+ ? <ProjectTasks key={projectContextId} within={projectContextId} disabled={disabled} />
46
+ : <p role="status">{prompt}</p>}
47
+ </section>
48
+ );
49
+ }
50
+
51
+ function ProjectTasks({ within, disabled }: { within: string; disabled: boolean }) {
52
+ const tasks = useTasks(within);
53
+ const [title, setTitle] = useState('');
54
+ const [selectedId, setSelectedId] = useState<string>();
55
+ async function addTask(event: FormEvent) {
56
+ event.preventDefault();
57
+ try {
58
+ const record = await tasks.create.mutateAsync({ title: title.trim(), completed: false });
59
+ if (tasks.create.isCurrent()) { setSelectedId(record.id); setTitle(''); }
60
+ } catch { /* The mutation error is rendered below. */ }
61
+ }
62
+ return <div className="project-content">
63
+ <h3>Tasks</h3>
64
+ <form className="demo-form" onSubmit={addTask}>
65
+ <label htmlFor="task-title">New task</label>
66
+ <input id="task-title" value={title} maxLength={120} required
67
+ disabled={disabled || tasks.create.isPending} onChange={(event) => setTitle(event.target.value)} />
68
+ <button className="button button-secondary" disabled={disabled || tasks.create.isPending || !title.trim()}>Add task</button>
69
+ </form>
70
+ {tasks.create.error && <p role="alert">Couldn’t add the task: {tasks.create.error.message}</p>}
71
+ {tasks.patch.error && <p role="alert">Couldn’t update the task: {tasks.patch.error.message}</p>}
72
+ {tasks.status === 'error' && <p role="alert">Couldn’t load tasks. <button type="button"
73
+ disabled={disabled} onClick={() => tasks.retry()}>Retry tasks</button></p>}
74
+ <ul className="task-list">
75
+ {tasks.records.map((task) => <li key={task.id} data-completed={task.data.completed}>
76
+ <input type="checkbox" aria-label={`Complete ${task.data.title}`} checked={task.data.completed}
77
+ disabled={disabled || tasks.patch.isPendingFor(task.id)}
78
+ onChange={(event) => tasks.patch.mutate({ id: task.id, patch: { completed: event.currentTarget.checked } })} />
79
+ <button type="button" className="button button-quiet" aria-label={`Open task ${task.data.title}`}
80
+ disabled={disabled} aria-pressed={task.id === selectedId} onClick={() => setSelectedId(task.id)}>{task.data.title}</button>
81
+ </li>)}
82
+ </ul>
83
+ {tasks.hasMore && <button type="button" disabled={disabled || tasks.isLoadingMore}
84
+ onClick={() => tasks.loadMore()}>More tasks</button>}
85
+ {selectedId !== undefined
86
+ ? <TaskDetails key={selectedId} within={within} recordId={selectedId} disabled={disabled} onClose={() => setSelectedId(undefined)} />
87
+ : <p role="status">Select a task to see its details.</p>}
88
+ </div>;
89
+ }
90
+
91
+ function TaskDetails({ within, recordId, disabled, onClose }: {
92
+ within: string; recordId: string; disabled: boolean; onClose: () => void;
93
+ }) {
94
+ const task = useTask(within, recordId);
95
+ const [draft, setDraft] = useState<string>();
96
+ const pending = task.patch.isPending || task.delete.isPending;
97
+ async function saveTitle(event: FormEvent) {
98
+ event.preventDefault();
99
+ if (draft === undefined) return;
100
+ try {
101
+ await task.patch.mutateAsync({ title: draft.trim() });
102
+ if (task.patch.isCurrent()) setDraft(undefined);
103
+ } catch { /* The mutation error is rendered below. */ }
104
+ }
105
+ async function deleteTask() {
106
+ try {
107
+ await task.delete.mutateAsync();
108
+ if (task.delete.isCurrent()) onClose();
109
+ } catch { /* The mutation error is rendered below. */ }
110
+ }
111
+ const data = task.data;
112
+ return <section className="task-details" aria-label="Task details">
113
+ <h3>Task details</h3>
114
+ {task.status === 'error' && <p role="alert">Couldn’t load the task. <button type="button"
115
+ disabled={disabled} onClick={() => task.retry()}>Retry task</button></p>}
116
+ {data === undefined && task.isLoading && <p role="status">Loading task…</p>}
117
+ {data === undefined && task.isReady && <p role="status">This task is no longer available.</p>}
118
+ {data !== undefined && <>
119
+ <p>{data.title} · {data.completed ? 'Completed' : 'To do'}</p>
120
+ {draft === undefined
121
+ ? <button type="button" className="button button-quiet" disabled={disabled || pending}
122
+ onClick={() => setDraft(data.title)}>Edit title</button>
123
+ : <form className="demo-form" onSubmit={saveTitle}>
124
+ <label htmlFor="edit-task-title">Task title</label>
125
+ <input id="edit-task-title" value={draft} maxLength={120} required disabled={disabled || pending}
126
+ onChange={(event) => setDraft(event.target.value)} />
127
+ <button className="button button-secondary" disabled={disabled || pending || !draft.trim()}>Save title</button>
128
+ <button type="button" className="button button-quiet" disabled={disabled || pending} onClick={() => setDraft(undefined)}>Cancel</button>
129
+ </form>}
130
+ <button type="button" className="button button-quiet" disabled={disabled || pending} onClick={deleteTask}>Delete task</button>
131
+ </>}
132
+ {task.patch.error && <p role="alert">Couldn’t update the task: {task.patch.error.message}</p>}
133
+ {task.delete.error && <p role="alert">Couldn’t delete the task: {task.delete.error.message}</p>}
134
+ <button type="button" className="button button-quiet" onClick={onClose}>Close details</button>
135
+ </section>;
136
+ }
@@ -0,0 +1,15 @@
1
+ .demo { padding: 30px; }
2
+ .demo > p { margin-top: 12px; color: var(--muted); font-size: .85rem; }
3
+ .demo [role="alert"] { color: #7d4533; }
4
+ .demo-form { display: grid; gap: .5rem; margin: 1rem 0; }
5
+ .demo-form input { padding: .65rem; border: 1px solid var(--border); border-radius: .5rem; font: inherit; background: transparent; color: inherit; }
6
+ .project-picker { display: flex; flex-wrap: wrap; gap: .5rem; margin: 1rem 0; }
7
+ .project-picker button[aria-pressed="true"], .task-list button[aria-pressed="true"] { background: #edf3e7; border-color: #709865; color: var(--accent); }
8
+ .project-content, .task-details { border-top: 1px solid var(--border); padding-top: 1rem; margin-top: 1rem; }
9
+ .task-list { padding: 0; list-style: none; }
10
+ .task-list li { display: flex; align-items: center; gap: .5rem; padding: .5rem 0; }
11
+ .task-list li[data-completed="true"] button { text-decoration: line-through; color: var(--muted); }
12
+ .task-list button { text-align: left; overflow-wrap: anywhere; }
13
+ @media (max-width: 600px) {
14
+ .demo { padding: 26px 20px; }
15
+ }
@@ -0,0 +1,26 @@
1
+ import { defineProtocol, recordCodecs } from '@enbox/react/config';
2
+
3
+ import app from '../app.json' with { type: 'json' };
4
+
5
+ export type Project = { name: string };
6
+ export type Task = { title: string; completed: boolean };
7
+
8
+ // Replace this example URI with one you own before publishing your app.
9
+ // Keep it stable after launch: it identifies the app's saved data and grants.
10
+ export const TaskBoardProtocol = defineProtocol({
11
+ protocol: `https://example.com/${encodeURIComponent(app.id)}/demo/v2`,
12
+ published: false,
13
+ types: {
14
+ project: { dataFormats: ['application/json'], encryptionRequired: true },
15
+ task: { dataFormats: ['application/json'], encryptionRequired: true },
16
+ },
17
+ structure: { project: { task: {} } },
18
+ } as const, {
19
+ project: recordCodecs.json<Project>({ validator: (value: unknown) =>
20
+ value !== null && typeof value === 'object' && !Array.isArray(value) && 'name' in value
21
+ && typeof value.name === 'string' && value.name.trim().length > 0 && value.name.length <= 60 }),
22
+ task: recordCodecs.json<Task>({ validator: (value: unknown) =>
23
+ value !== null && typeof value === 'object' && !Array.isArray(value) && 'title' in value && 'completed' in value
24
+ && typeof value.title === 'string' && value.title.trim().length > 0 && value.title.length <= 120
25
+ && typeof value.completed === 'boolean' }),
26
+ });
@@ -0,0 +1,16 @@
1
+ import { useEnboxRecord, useEnboxRecords } from '@enbox/react';
2
+ import { DateSort } from '@enbox/react/config';
3
+
4
+ import { TaskBoardProtocol } from './protocol.js';
5
+
6
+ export function useProjects() {
7
+ return useEnboxRecords(TaskBoardProtocol, 'project', { dateSort: DateSort.CreatedDescending });
8
+ }
9
+
10
+ export function useTasks(within: string) {
11
+ return useEnboxRecords(TaskBoardProtocol, 'project/task', { within });
12
+ }
13
+
14
+ export function useTask(within: string, recordId: string) {
15
+ return useEnboxRecord(TaskBoardProtocol, 'project/task', { within, recordId });
16
+ }
@@ -0,0 +1,18 @@
1
+ import { prepareBrowser } from '@enbox/browser';
2
+ import { EnboxProvider } from '@enbox/react';
3
+ import { StrictMode } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+
6
+ import { App } from './App.js';
7
+ import { config } from './application.js';
8
+ import workerPath from './sw.ts?worker&url';
9
+ import './style.css';
10
+
11
+ void prepareBrowser(workerPath, {
12
+ registrationOptions: { type: 'module', scope: import.meta.env.BASE_URL },
13
+ }).then(() => {
14
+ createRoot(document.getElementById('root')!).render(<StrictMode><EnboxProvider config={config}><App /></EnboxProvider></StrictMode>);
15
+ }).catch((cause: unknown) => {
16
+ const root = document.getElementById('root')!;
17
+ root.textContent = cause instanceof Error ? cause.message : 'Could not open the app.';
18
+ });
@@ -0,0 +1,108 @@
1
+ :root {
2
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
3
+ color: #27342e;
4
+ background: #f6f5f0;
5
+ font-synthesis: none;
6
+ text-rendering: optimizeLegibility;
7
+ -webkit-font-smoothing: antialiased;
8
+ color-scheme: light;
9
+ --muted: #68716b;
10
+ --accent: #315b46;
11
+ --border: #e1e4dc;
12
+ }
13
+
14
+ * { box-sizing: border-box; }
15
+ body { margin: 0; min-width: 320px; }
16
+ button, input { font: inherit; }
17
+ button { cursor: pointer; }
18
+ button:disabled { cursor: default; opacity: .52; }
19
+ :focus-visible { outline: 3px solid #709e76; outline-offset: 4px; }
20
+ a { color: inherit; }
21
+ p { margin: 0; line-height: 1.65; }
22
+ h1, h2 { margin: 0; line-height: 1.15; }
23
+ h2 { font-size: 1.3rem; font-weight: 600; letter-spacing: -.035em; }
24
+
25
+ .app-shell { max-width: 1040px; margin: 0 auto; padding: 0 36px; }
26
+ .app-header {
27
+ min-height: 108px;
28
+ display: flex;
29
+ align-items: center;
30
+ justify-content: space-between;
31
+ gap: 16px;
32
+ }
33
+ .wordmark { display: inline-flex; gap: 10px; align-items: center; text-decoration: none; font-size: .8rem; font-weight: 600; }
34
+ .brand-symbol {
35
+ width: 28px;
36
+ height: 28px;
37
+ display: grid;
38
+ place-items: center;
39
+ border-radius: 9px;
40
+ background: var(--accent);
41
+ color: #fff;
42
+ font: italic 25px/.9 Georgia, serif;
43
+ }
44
+ main { max-width: 640px; margin: 45px auto 0; }
45
+ .intro { margin-bottom: 36px; }
46
+ .eyebrow { color: var(--muted); font-size: .65rem; font-weight: 650; letter-spacing: .14em; text-transform: uppercase; }
47
+ .intro h1 { margin: 10px 0 15px; font-family: Georgia, "Times New Roman", serif; font-size: clamp(2.9rem, 7vw, 4.3rem); font-weight: 400; letter-spacing: -.065em; overflow-wrap: anywhere; }
48
+ .intro > p:last-child { color: var(--muted); font-size: .94rem; }
49
+ .panel { background: #fff; border: 1px solid var(--border); border-radius: 22px; box-shadow: 0 6px 24px #27342e04; }
50
+ .connected-content { display: grid; gap: 20px; }
51
+
52
+ .button { display: inline-flex; align-items: center; justify-content: center; gap: 18px; min-height: 42px; padding: 10px 17px; border: 1px solid transparent; border-radius: 10px; font-size: .84rem; font-weight: 550; transition: background .15s, border-color .15s; }
53
+ .button-primary { background: var(--accent); color: #fff; }
54
+ .button-primary:hover:not(:disabled) { background: #264836; }
55
+ .button-secondary { background: #fff; color: var(--accent); border-color: #b8ccbb; }
56
+ .button-secondary:hover:not(:disabled) { background: #f3f7f0; }
57
+ .button-quiet { background: transparent; border-color: var(--border); color: var(--muted); font-size: .77rem; min-height: 36px; }
58
+ .button-quiet:hover:not(:disabled) { border-color: #a6b4a7; color: var(--accent); }
59
+
60
+ .connect-panel { padding: 42px 40px; text-align: center; }
61
+ .welcome-symbol { display: grid; place-items: center; width: 66px; height: 66px; margin: 0 auto 25px; border-radius: 22px; color: var(--accent); background: #eef2e8; font-size: 2.6rem; }
62
+ .connect-panel h2 { font-size: 1.45rem; }
63
+ .connect-panel > p { max-width: 350px; margin: 13px auto 24px; color: var(--muted); font-size: .88rem; }
64
+ .connect-panel .button { min-width: 190px; }
65
+ .connect-panel .connect-caption { margin: 14px 0 0; max-width: none; font-size: .73rem; }
66
+
67
+ .profile-card { padding: 24px 26px; }
68
+ .profile-heading { display: flex; align-items: center; gap: 15px; }
69
+ .avatar { display: grid; place-items: center; width: 52px; height: 52px; flex: 0 0 auto; overflow: hidden; border-radius: 50%; background: #edece5; color: #626d59; font: 1.15rem Georgia, serif; }
70
+ .avatar img { width: 100%; height: 100%; object-fit: cover; }
71
+ .profile-identity { min-width: 0; flex: 1; }
72
+ .profile-identity .eyebrow { font-size: .58rem; letter-spacing: .1em; }
73
+ .profile-identity h2 { font-size: 1.08rem; margin: 5px 0; overflow-wrap: anywhere; }
74
+ .short-did { color: var(--muted); font-size: .69rem; font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
75
+ .connected-badge { display: inline-flex; align-items: center; gap: 6px; color: var(--accent); font-size: .65rem; white-space: nowrap; }
76
+ .connected-badge > span { width: 5px; height: 5px; background: #638b5b; border-radius: 50%; }
77
+ .profile-card > p { margin-top: 16px; color: var(--muted); font-size: .8rem; }
78
+ .profile-details { border-top: 1px solid #edf0e8; margin-top: 20px; padding-top: 13px; }
79
+ .profile-details summary { width: fit-content; cursor: pointer; color: var(--muted); font-size: .74rem; }
80
+ .profile-details summary:hover { color: var(--accent); }
81
+ .profile-details dl { margin: 18px 0 0; font-size: .78rem; }
82
+ .profile-details dt { margin-top: 12px; color: var(--muted); font-size: .69rem; }
83
+ .profile-details dd { margin: 4px 0 0; overflow-wrap: anywhere; }
84
+ .profile-details code { font-family: ui-monospace, monospace; font-size: .72rem; }
85
+ .profile-bio { margin-top: 15px; color: var(--muted); font-size: .82rem; white-space: pre-wrap; }
86
+
87
+ .notice { margin-bottom: 18px; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; border: 1px solid #ccd9c5; border-radius: 13px; padding: 15px 18px; background: #edf3e8; font-size: .82rem; }
88
+ .notice p { flex-basis: 100%; }
89
+ .notice strong { font-weight: 600; }
90
+ .notice-error { background: #fff5ef; border-color: #eed2c3; color: #7d4533; }
91
+ .error-detail { font-size: .73rem; overflow-wrap: anywhere; }
92
+ .app-footer { padding: 38px 0; color: #7f857e; text-align: center; font-size: .69rem; }
93
+ .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
94
+
95
+ @media (max-width: 600px) {
96
+ .app-shell { padding: 0 20px; }
97
+ .app-header { min-height: 84px; }
98
+ main { margin-top: 27px; }
99
+ .intro { margin-bottom: 27px; }
100
+ .connect-panel { padding: 34px 22px; }
101
+ .profile-card { padding: 22px 20px; }
102
+ .connected-badge { align-self: flex-start; margin-top: 4px; font-size: 0; }
103
+ .connected-badge > span { width: 7px; height: 7px; }
104
+ .app-footer { font-size: .65rem; }
105
+ }
106
+ @media (prefers-reduced-motion: reduce) {
107
+ .button { transition: none; }
108
+ }
@@ -0,0 +1,40 @@
1
+ /// <reference lib="webworker" />
2
+ import { activatePolyfills } from '@enbox/browser';
3
+
4
+ declare let self: ServiceWorkerGlobalScope;
5
+ declare const __APP_SHELL__: { version: string; files: string[] };
6
+
7
+ // Vite injects only production outputs; development uses its live module server.
8
+ if (import.meta.env.PROD) {
9
+ const shell = __APP_SHELL__;
10
+ const prefix = `enbox-shell:${self.registration.scope}:`;
11
+ const cacheName = `${prefix}${shell.version}`;
12
+ const root = new URL(self.registration.scope);
13
+ const index = new URL('index.html', root);
14
+ const files = shell.files.map((file) => new URL(file, self.registration.scope).href);
15
+
16
+ self.addEventListener('install', (event) => {
17
+ event.waitUntil(caches.open(cacheName).then((cache) =>
18
+ cache.addAll(files.map((url) => new Request(url, { cache: 'reload' })))));
19
+ });
20
+ self.addEventListener('activate', (event) => {
21
+ event.waitUntil(caches.keys().then((names) => Promise.all(
22
+ names.filter((name) => name.startsWith(prefix) && name !== cacheName).map((name) => caches.delete(name)),
23
+ )));
24
+ });
25
+ self.addEventListener('fetch', (event) => {
26
+ if (event.request.method !== 'GET') return;
27
+ const url = new URL(event.request.url);
28
+ // This starter has no router: leave other navigation and API routes alone.
29
+ const isIndex = event.request.mode === 'navigate' && url.origin === index.origin &&
30
+ (url.pathname === index.pathname || url.pathname === root.pathname);
31
+ const target = isIndex ? index.href : url.href;
32
+ if (files.includes(target)) {
33
+ event.respondWith(caches.open(cacheName).then(async (cache) =>
34
+ await cache.match(target) ?? fetch(event.request)));
35
+ }
36
+ });
37
+ }
38
+
39
+ // The current browser SDK performs automatic worker takeover.
40
+ activatePolyfills({ onCacheCheck: () => ({ ttl: 30_000 }) });
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler",
7
+ "jsx": "react-jsx",
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "exactOptionalPropertyTypes": true,
11
+ "noUnusedLocals": true,
12
+ "noUnusedParameters": true,
13
+ "verbatimModuleSyntax": true,
14
+ "resolveJsonModule": true,
15
+ "skipLibCheck": true,
16
+ "noEmit": true,
17
+ "types": ["vite/client", "node"]
18
+ },
19
+ "include": ["src", "vite.config.ts"]
20
+ }
@@ -0,0 +1,47 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ import react from '@vitejs/plugin-react';
5
+ import { defineConfig, normalizePath } from 'vite';
6
+
7
+ const appWorker = normalizePath(fileURLToPath(new URL('./src/sw.ts', import.meta.url)));
8
+
9
+ export default defineConfig({
10
+ plugins: [
11
+ react(),
12
+ {
13
+ name: 'app-shell',
14
+ apply: 'build',
15
+ generateBundle: {
16
+ // Wait for Vite to emit the worker and finalize index.html.
17
+ order: 'post',
18
+ handler(_options, bundle) {
19
+ const worker = bundle['sw.js'];
20
+ if (worker?.type !== 'asset' || typeof worker.source !== 'string') {
21
+ this.error('The app service worker was not emitted.');
22
+ }
23
+ const files = Object.keys(bundle).filter((file) => !file.endsWith('.map')).sort();
24
+ const hash = createHash('sha256');
25
+ for (const file of files) {
26
+ const output = bundle[file]!;
27
+ hash.update(file).update('\0').update(output.type === 'chunk' ? output.code : output.source);
28
+ }
29
+ worker.source = worker.source.replace('__APP_SHELL__', JSON.stringify({
30
+ version: hash.digest('hex').slice(0, 16),
31
+ files: files.filter((file) => file !== 'sw.js'),
32
+ }));
33
+ },
34
+ },
35
+ },
36
+ ],
37
+ worker: {
38
+ format: 'es',
39
+ rollupOptions: {
40
+ output: {
41
+ entryFileNames: ({ facadeModuleId }) => facadeModuleId === appWorker ? 'sw.js' : 'assets/[name]-[hash].js',
42
+ },
43
+ },
44
+ },
45
+ server: { host: '127.0.0.1', headers: { 'Service-Worker-Allowed': '/' } },
46
+ preview: { host: '127.0.0.1' },
47
+ });