@cadence-app/compiler 0.1.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -0
  3. package/dist/build.d.ts +31 -0
  4. package/dist/build.js +437 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +180 -0
  7. package/dist/dev-server.d.ts +16 -0
  8. package/dist/dev-server.js +81 -0
  9. package/dist/engine-budget.d.ts +9 -0
  10. package/dist/engine-budget.js +8 -0
  11. package/dist/hash.d.ts +2 -0
  12. package/dist/hash.js +12 -0
  13. package/dist/host/browser-mock-host.d.ts +1 -0
  14. package/dist/host/browser-mock-host.js +175 -0
  15. package/dist/host/dev-client.d.ts +1 -0
  16. package/dist/host/dev-client.js +6 -0
  17. package/dist/host/engine-entry.d.ts +1 -0
  18. package/dist/host/engine-entry.js +199 -0
  19. package/dist/index.d.ts +23 -0
  20. package/dist/index.js +14 -0
  21. package/dist/manifest.d.ts +47 -0
  22. package/dist/manifest.js +202 -0
  23. package/dist/publish/credentials.d.ts +17 -0
  24. package/dist/publish/credentials.js +87 -0
  25. package/dist/publish/distribution-client.d.ts +45 -0
  26. package/dist/publish/distribution-client.js +113 -0
  27. package/dist/publish/publish-bundle.d.ts +27 -0
  28. package/dist/publish/publish-bundle.js +44 -0
  29. package/dist/publish/publish-errors.d.ts +41 -0
  30. package/dist/publish/publish-errors.js +60 -0
  31. package/dist/publish/read-secret.d.ts +7 -0
  32. package/dist/publish/read-secret.js +30 -0
  33. package/dist/style/compile-style.d.ts +13 -0
  34. package/dist/style/compile-style.js +135 -0
  35. package/dist/style/theme-sheet.d.ts +6 -0
  36. package/dist/style/theme-sheet.js +8 -0
  37. package/dist/template/ast.d.ts +47 -0
  38. package/dist/template/ast.js +1 -0
  39. package/dist/template/codegen.d.ts +8 -0
  40. package/dist/template/codegen.js +220 -0
  41. package/dist/template/entities.d.ts +12 -0
  42. package/dist/template/entities.js +103 -0
  43. package/dist/template/expression.d.ts +16 -0
  44. package/dist/template/expression.js +196 -0
  45. package/dist/template/parser.d.ts +10 -0
  46. package/dist/template/parser.js +437 -0
  47. package/package.json +62 -0
package/dist/cli.js ADDED
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { buildMiniApp } from "./build.js";
5
+ import { startDevServer } from "./dev-server.js";
6
+ import { ENGINE_GZIP_BUDGET_BYTES, engineBudgetVerdict } from "./engine-budget.js";
7
+ import { clearCredentials, credentialsPath, normalizeRemoteUrl, readCredentials, writeCredentials, } from "./publish/credentials.js";
8
+ import { DistributionClient } from "./publish/distribution-client.js";
9
+ import { publishMiniApp } from "./publish/publish-bundle.js";
10
+ import { readSecret } from "./publish/read-secret.js";
11
+ const DEFAULT_DEV_PORT = 4173;
12
+ const HELP = `mini — outillage des mini-programmes Cadence
13
+
14
+ Compiler :
15
+ mini build <dossier-miniapp> [--out <dossier>] [--minify] [--no-zip]
16
+ mini dev <dossier-miniapp> [--out <dossier>] [--port <n>]
17
+
18
+ Publier :
19
+ mini login --remote <url> [--token <pat>]
20
+ mini logout
21
+ mini whoami
22
+ mini publish <dossier-miniapp> [--app-id <uuid>]
23
+ `;
24
+ /** Commandes qui parlent au serveur plutôt qu'à un dossier de sources. */
25
+ const ACCOUNT_COMMANDS = new Set(['login', 'logout', 'whoami']);
26
+ async function main() {
27
+ const { values, positionals } = parseArgs({
28
+ args: process.argv.slice(2),
29
+ allowPositionals: true,
30
+ options: {
31
+ out: { type: 'string' },
32
+ minify: { type: 'boolean', default: false },
33
+ 'no-zip': { type: 'boolean', default: false },
34
+ port: { type: 'string' },
35
+ remote: { type: 'string' },
36
+ token: { type: 'string' },
37
+ 'app-id': { type: 'string' },
38
+ help: { type: 'boolean', default: false },
39
+ },
40
+ });
41
+ const [command, miniappDirArg] = positionals;
42
+ if (values.help === true || command === undefined) {
43
+ console.log(HELP);
44
+ return;
45
+ }
46
+ if (ACCOUNT_COMMANDS.has(command)) {
47
+ await runAccountCommand(command, values);
48
+ return;
49
+ }
50
+ if (miniappDirArg === undefined) {
51
+ exitWith(`le dossier du mini-programme est requis\n\n${HELP}`);
52
+ }
53
+ const miniappDir = path.resolve(miniappDirArg);
54
+ if (command === 'publish') {
55
+ const report = await publishMiniApp({
56
+ miniappDir,
57
+ ...(values['app-id'] === undefined ? {} : { appId: values['app-id'] }),
58
+ });
59
+ printPublishReport(report);
60
+ return;
61
+ }
62
+ if (command === 'build') {
63
+ const summary = await buildMiniApp({
64
+ miniappDir,
65
+ minify: values.minify === true,
66
+ zip: values['no-zip'] !== true,
67
+ ...(values.out === undefined ? {} : { outDir: values.out }),
68
+ });
69
+ printSummary(summary);
70
+ return;
71
+ }
72
+ if (command === 'dev') {
73
+ const outDir = values.out ?? path.join(miniappDir, 'dist');
74
+ const rebuild = async () => {
75
+ await buildMiniApp({ miniappDir, outDir, minify: false, zip: false });
76
+ };
77
+ await rebuild();
78
+ const port = values.port === undefined ? DEFAULT_DEV_PORT : Number(values.port);
79
+ const server = startDevServer({
80
+ distDir: path.resolve(outDir),
81
+ watchDir: miniappDir,
82
+ port,
83
+ rebuild,
84
+ });
85
+ console.log(`mini dev — ${server.url}`);
86
+ console.log(' navigateur : mock natif intégré (Échap = retour)');
87
+ console.log(` app hôte : pointer le conteneur Flutter sur ${server.url}index.html`);
88
+ return;
89
+ }
90
+ exitWith(`commande inconnue '${command}'\n\n${HELP}`);
91
+ }
92
+ async function runAccountCommand(command, values) {
93
+ if (command === 'logout') {
94
+ const removed = await clearCredentials();
95
+ console.log(removed ? `identifiants effacés — ${credentialsPath()}` : 'aucun identifiant à effacer');
96
+ return;
97
+ }
98
+ if (command === 'whoami') {
99
+ const credentials = await readCredentials();
100
+ if (credentials === null) {
101
+ exitWith("aucun identifiant enregistré — lancer « mini login » d'abord");
102
+ }
103
+ await new DistributionClient(credentials).verifyToken();
104
+ console.log(`connecté à ${credentials.remoteUrl}`);
105
+ console.log(` jeton : ${maskToken(credentials.token)} (accepté)`);
106
+ console.log(` fichier : ${credentialsPath()}`);
107
+ return;
108
+ }
109
+ const remote = values.remote ?? (await readCredentials())?.remoteUrl;
110
+ if (remote === undefined || remote === '') {
111
+ exitWith(`l'adresse du serveur est requise\n\n mini login --remote https://api.exemple.fr`);
112
+ }
113
+ const token = values.token ?? (await readSecret("jeton d'accès (invisible) : "));
114
+ if (token === '') {
115
+ exitWith("aucun jeton fourni — générer un jeton d'accès personnel sur le serveur");
116
+ }
117
+ const remoteUrl = normalizeRemoteUrl(remote);
118
+ // Vérifier avant d'écrire : un jeton refusé enregistré est un piège qui ne
119
+ // se révèle qu'à la première publication.
120
+ await new DistributionClient({ remoteUrl, token }).verifyToken();
121
+ const file = await writeCredentials({ remoteUrl, token });
122
+ console.log(`connecté à ${remoteUrl}`);
123
+ console.log(` jeton : ${maskToken(token)}`);
124
+ console.log(` fichier : ${file} (lisible par vous seul)`);
125
+ }
126
+ function printPublishReport(report) {
127
+ const sizeKo = (report.archiveBytes / 1024).toFixed(1);
128
+ console.log(`publié « ${report.slug} » v${report.published.versionString} → ${report.remoteUrl}`);
129
+ console.log(` archive : ${path.basename(report.archivePath)} (${sizeKo} ko)`);
130
+ console.log(` app : ${report.appId}`);
131
+ if (report.published.status !== null) {
132
+ console.log(` statut : ${report.published.status}`);
133
+ }
134
+ if (report.published.createdAt !== null) {
135
+ console.log(` créée le : ${report.published.createdAt}`);
136
+ }
137
+ }
138
+ /** Un jeton ne s'affiche jamais en entier, pas même à son porteur. */
139
+ function maskToken(token) {
140
+ const VISIBLE = 4;
141
+ return token.length <= VISIBLE ? '•'.repeat(token.length) : `${token.slice(0, VISIBLE)}…`;
142
+ }
143
+ function printSummary(summary) {
144
+ const engineGzipKo = (summary.engine.gzip / 1024).toFixed(1);
145
+ const appGzipKo = (summary.app.gzip / 1024).toFixed(1);
146
+ const budgetVerdict = engineBudgetVerdict(summary);
147
+ console.log(`bundle « ${summary.manifest.name} » v${summary.manifest.version} → ${summary.outDir}`);
148
+ console.log(` pages : ${summary.pageRoutes.join(', ')}`);
149
+ if (summary.componentTags.length > 0) {
150
+ console.log(` composants : ${summary.componentTags.join(', ')}`);
151
+ }
152
+ if (summary.subPackageFiles.length > 0) {
153
+ console.log(` sous-packages : ${summary.subPackageFiles.join(', ')}`);
154
+ }
155
+ console.log(` engine.js : ${engineGzipKo} ko gzip (${describeEngineBudget(budgetVerdict)})`);
156
+ console.log(` app.js : ${appGzipKo} ko gzip`);
157
+ if (summary.zipFile !== null) {
158
+ console.log(` archive : ${summary.zipFile}`);
159
+ }
160
+ if (budgetVerdict === 'exceeded') {
161
+ process.exitCode = 1;
162
+ }
163
+ }
164
+ function describeEngineBudget(verdict) {
165
+ const budget = `budget ${ENGINE_GZIP_BUDGET_BYTES / 1024} ko`;
166
+ const descriptions = {
167
+ within: `${budget} : OK`,
168
+ exceeded: `${budget} : DÉPASSÉ`,
169
+ 'not-measured': `non minifié — ${budget} jugé avec --minify`,
170
+ };
171
+ return descriptions[verdict];
172
+ }
173
+ function exitWith(message) {
174
+ console.error(message);
175
+ process.exit(1);
176
+ }
177
+ main().catch((error) => {
178
+ console.error(error instanceof Error ? `${error.name}: ${error.message}` : error);
179
+ process.exit(1);
180
+ });
@@ -0,0 +1,16 @@
1
+ export interface DevServerOptions {
2
+ readonly distDir: string;
3
+ readonly watchDir: string;
4
+ readonly port: number;
5
+ readonly rebuild: () => Promise<void>;
6
+ }
7
+ export interface DevServer {
8
+ readonly url: string;
9
+ close(): void;
10
+ }
11
+ /**
12
+ * Serveur `mini dev` : sert le bundle compilé, surveille les sources du
13
+ * mini-programme et pousse un événement SSE de rechargement après chaque
14
+ * rebuild réussi.
15
+ */
16
+ export declare function startDevServer(options: DevServerOptions): DevServer;
@@ -0,0 +1,81 @@
1
+ import { existsSync, watch } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import http from 'node:http';
4
+ import path from 'node:path';
5
+ const CONTENT_TYPES = {
6
+ '.html': 'text/html; charset=utf-8',
7
+ '.js': 'text/javascript; charset=utf-8',
8
+ '.css': 'text/css; charset=utf-8',
9
+ '.json': 'application/json; charset=utf-8',
10
+ '.png': 'image/png',
11
+ '.jpg': 'image/jpeg',
12
+ '.svg': 'image/svg+xml',
13
+ '.zip': 'application/zip',
14
+ };
15
+ const REBUILD_DEBOUNCE_MS = 150;
16
+ /**
17
+ * Serveur `mini dev` : sert le bundle compilé, surveille les sources du
18
+ * mini-programme et pousse un événement SSE de rechargement après chaque
19
+ * rebuild réussi.
20
+ */
21
+ export function startDevServer(options) {
22
+ const sseClients = new Set();
23
+ const server = http.createServer((request, response) => {
24
+ void handleRequest(request, response);
25
+ });
26
+ async function handleRequest(request, response) {
27
+ const url = (request.url ?? '/').split('?')[0] ?? '/';
28
+ if (url === '/__cadence_dev') {
29
+ response.writeHead(200, {
30
+ 'Content-Type': 'text/event-stream',
31
+ 'Cache-Control': 'no-cache',
32
+ Connection: 'keep-alive',
33
+ });
34
+ response.write(': connected\n\n');
35
+ sseClients.add(response);
36
+ request.on('close', () => sseClients.delete(response));
37
+ return;
38
+ }
39
+ const relativePath = url === '/' ? 'dev.html' : url.slice(1);
40
+ const filePath = path.join(options.distDir, relativePath);
41
+ if (!filePath.startsWith(options.distDir) || !existsSync(filePath)) {
42
+ response.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
43
+ response.end(`404 — ${relativePath}`);
44
+ return;
45
+ }
46
+ const contentType = CONTENT_TYPES[path.extname(filePath)] ?? 'application/octet-stream';
47
+ response.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-store' });
48
+ response.end(await readFile(filePath));
49
+ }
50
+ let rebuildTimer = null;
51
+ const watcher = watch(options.watchDir, { recursive: true }, (_event, fileName) => {
52
+ if (fileName !== null && fileName.startsWith('dist')) {
53
+ return;
54
+ }
55
+ if (rebuildTimer !== null) {
56
+ clearTimeout(rebuildTimer);
57
+ }
58
+ rebuildTimer = setTimeout(() => {
59
+ options
60
+ .rebuild()
61
+ .then(() => {
62
+ console.warn(`[cadence dev] rebuild ok (${fileName ?? 'watch'})`);
63
+ for (const client of sseClients) {
64
+ client.write('event: reload\ndata: {}\n\n');
65
+ }
66
+ })
67
+ .catch((error) => console.error('[cadence dev] rebuild failed:', error));
68
+ }, REBUILD_DEBOUNCE_MS);
69
+ });
70
+ server.listen(options.port);
71
+ return {
72
+ url: `http://localhost:${options.port}/`,
73
+ close() {
74
+ watcher.close();
75
+ for (const client of sseClients) {
76
+ client.end();
77
+ }
78
+ server.close();
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,9 @@
1
+ import type { BuildSummary } from './build.js';
2
+ /** Le budget du moteur, minifié puis gzippé (CLAUDE.md §9). */
3
+ export declare const ENGINE_GZIP_BUDGET_BYTES: number;
4
+ /**
5
+ * `not-measured` pour un moteur que le build n'a pas minifié : le même code y pèse près de moitié
6
+ * plus, et le budget, fixé sur le moteur qu'on livre, le déclarerait dépassé à tort.
7
+ */
8
+ export type EngineBudgetVerdict = 'within' | 'exceeded' | 'not-measured';
9
+ export declare function engineBudgetVerdict(build: Pick<BuildSummary, 'minified' | 'engine'>): EngineBudgetVerdict;
@@ -0,0 +1,8 @@
1
+ /** Le budget du moteur, minifié puis gzippé (CLAUDE.md §9). */
2
+ export const ENGINE_GZIP_BUDGET_BYTES = 30 * 1024;
3
+ export function engineBudgetVerdict(build) {
4
+ if (!build.minified) {
5
+ return 'not-measured';
6
+ }
7
+ return build.engine.gzip <= ENGINE_GZIP_BUDGET_BYTES ? 'within' : 'exceeded';
8
+ }
package/dist/hash.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Hash court, stable et déterministe : identifie un composant/une page entre builds. */
2
+ export declare function stableHash(input: string): string;
package/dist/hash.js ADDED
@@ -0,0 +1,12 @@
1
+ const FNV_OFFSET_BASIS = 0x811c9dc5;
2
+ const FNV_PRIME = 0x01000193;
3
+ const STYLE_ID_LENGTH = 8;
4
+ /** Hash court, stable et déterministe : identifie un composant/une page entre builds. */
5
+ export function stableHash(input) {
6
+ let hash = FNV_OFFSET_BASIS;
7
+ for (let i = 0; i < input.length; i += 1) {
8
+ hash ^= input.charCodeAt(i);
9
+ hash = Math.imul(hash, FNV_PRIME);
10
+ }
11
+ return (hash >>> 0).toString(36).padStart(STYLE_ID_LENGTH, '0').slice(0, STYLE_ID_LENGTH);
12
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,175 @@
1
+ import { BridgeEvents, BridgeMethods, InProcessHost, createLinkedTransportPair, } from '@cadence-app/bridge';
2
+ import { NORMAL_TEXT_SCALE } from '@cadence-app/runtime';
3
+ /**
4
+ * Conteneur natif simulé pour `mini dev` dans un navigateur : storage sur
5
+ * localStorage, toasts/dialogues/loading en DOM, infos système depuis la
6
+ * fenêtre. Permet de développer un mini-programme sans lancer Flutter.
7
+ */
8
+ const STORAGE_PREFIX = 'cadence-dev:';
9
+ const pair = createLinkedTransportPair();
10
+ globalThis.__cadenceDevTransport = pair.left;
11
+ const host = new InProcessHost(pair.right);
12
+ host.handle(BridgeMethods.storageGet, (payload) => {
13
+ const { key } = payload;
14
+ const raw = localStorage.getItem(`${STORAGE_PREFIX}${key}`);
15
+ return { value: raw === null ? null : JSON.parse(raw) };
16
+ });
17
+ host.handle(BridgeMethods.storageSet, (payload) => {
18
+ const { key, value } = payload;
19
+ localStorage.setItem(`${STORAGE_PREFIX}${key}`, JSON.stringify(value ?? null));
20
+ return null;
21
+ });
22
+ host.handle(BridgeMethods.storageRemove, (payload) => {
23
+ localStorage.removeItem(`${STORAGE_PREFIX}${payload.key}`);
24
+ return null;
25
+ });
26
+ host.handle(BridgeMethods.storageClear, () => {
27
+ for (const key of Object.keys(localStorage)) {
28
+ if (key.startsWith(STORAGE_PREFIX)) {
29
+ localStorage.removeItem(key);
30
+ }
31
+ }
32
+ return null;
33
+ });
34
+ const TOAST_DURATION_MS = 2000;
35
+ /** Dans le navigateur, l'hôte c'est lui : sa langue est celle de l'application hôte. */
36
+ function hostLanguage() {
37
+ return navigator.language;
38
+ }
39
+ const ENGLISH_DIALOG_BUTTONS = { confirm: 'OK', cancel: 'Cancel' };
40
+ const FRENCH_DIALOG_BUTTONS = { confirm: 'OK', cancel: 'Annuler' };
41
+ /* La règle de `MiniAppStrings.forLocale`, dans le conteneur Flutter : en
42
+ développement, les boutons par défaut sont ceux que montrerait un hôte qui
43
+ ne pose pas ses propres libellés. */
44
+ function defaultDialogButtonsFor(language) {
45
+ return new Intl.Locale(language).language === 'fr'
46
+ ? FRENCH_DIALOG_BUTTONS
47
+ : ENGLISH_DIALOG_BUTTONS;
48
+ }
49
+ host.handle(BridgeMethods.uiShowToast, (payload) => {
50
+ const { title, icon } = payload;
51
+ const toast = document.createElement('div');
52
+ toast.textContent = icon === 'success' ? `✓ ${title}` : icon === 'error' ? `✕ ${title}` : title;
53
+ toast.setAttribute('style', 'position:fixed;left:50%;bottom:12%;transform:translateX(-50%);background:rgba(20,20,20,.85);color:#fff;' +
54
+ 'padding:10px 18px;border-radius:8px;font:14px -apple-system,sans-serif;z-index:9999;max-width:70vw;text-align:center;');
55
+ document.body.appendChild(toast);
56
+ setTimeout(() => toast.remove(), TOAST_DURATION_MS);
57
+ return null;
58
+ });
59
+ host.handle(BridgeMethods.uiShowDialog, (payload) => {
60
+ const { title, content, confirmText, cancelText } = payload;
61
+ return new Promise((resolve) => {
62
+ const overlay = document.createElement('div');
63
+ overlay.setAttribute('style', 'position:fixed;inset:0;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;z-index:9999;');
64
+ const box = document.createElement('div');
65
+ box.setAttribute('style', 'background:#fff;border-radius:12px;max-width:80vw;min-width:260px;overflow:hidden;font-family:-apple-system,sans-serif;');
66
+ box.innerHTML =
67
+ `<div style="padding:20px 20px 8px;font-weight:600;text-align:center;">${escapeHtml(title)}</div>` +
68
+ `<div style="padding:0 20px 20px;color:#555;text-align:center;font-size:14px;">${escapeHtml(content)}</div>`;
69
+ const buttons = document.createElement('div');
70
+ buttons.setAttribute('style', 'display:flex;border-top:1px solid #eee;');
71
+ const finish = (confirmed) => {
72
+ overlay.remove();
73
+ resolve({ confirmed });
74
+ };
75
+ const defaults = defaultDialogButtonsFor(hostLanguage());
76
+ buttons.appendChild(makeDialogButton(cancelText ?? defaults.cancel, '#555', () => finish(false)));
77
+ buttons.appendChild(makeDialogButton(confirmText ?? defaults.confirm, '#07c160', () => finish(true)));
78
+ box.appendChild(buttons);
79
+ overlay.appendChild(box);
80
+ document.body.appendChild(overlay);
81
+ });
82
+ });
83
+ let loadingOverlay = null;
84
+ /* Le `_LoadingCard` du conteneur n'écrit rien sans titre : aucun libellé à traduire ici. */
85
+ host.handle(BridgeMethods.uiShowLoading, (payload) => {
86
+ const { title } = payload;
87
+ hideLoading();
88
+ loadingOverlay = document.createElement('div');
89
+ loadingOverlay.setAttribute('style', 'position:fixed;inset:0;display:flex;flex-direction:column;gap:10px;align-items:center;justify-content:center;' +
90
+ 'background:rgba(255,255,255,.6);z-index:9998;font-family:-apple-system,sans-serif;color:#333;');
91
+ loadingOverlay.append(document.createElement('progress'));
92
+ if (typeof title === 'string') {
93
+ loadingOverlay.append(title);
94
+ }
95
+ document.body.appendChild(loadingOverlay);
96
+ return null;
97
+ });
98
+ host.handle(BridgeMethods.uiHideLoading, () => {
99
+ hideLoading();
100
+ return null;
101
+ });
102
+ /** Zones sûres simulées : de quoi voir en développement ce que donnera une encoche. */
103
+ const MOCK_SAFE_AREA = { top: 44, bottom: 24, left: 0, right: 0 };
104
+ const MOCK_CAPSULE = { top: MOCK_SAFE_AREA.top + 8, right: 12, width: 88, height: 32 };
105
+ const darkSchemeQuery = window.matchMedia('(prefers-color-scheme: dark)');
106
+ function currentColorScheme() {
107
+ return darkSchemeQuery.matches ? 'dark' : 'light';
108
+ }
109
+ host.handle(BridgeMethods.systemGetSystemInfo, () => ({
110
+ platform: 'web-dev',
111
+ colorScheme: currentColorScheme(),
112
+ /* Le navigateur de bureau n'a pas d'hôte dont suivre la taille du texte. */
113
+ textScale: NORMAL_TEXT_SCALE,
114
+ language: hostLanguage(),
115
+ screenWidth: window.innerWidth,
116
+ screenHeight: window.innerHeight,
117
+ pixelRatio: window.devicePixelRatio,
118
+ safeAreaInsets: MOCK_SAFE_AREA,
119
+ capsule: MOCK_CAPSULE,
120
+ }));
121
+ host.handle(BridgeMethods.uiSetStatusBarIcons, (payload) => {
122
+ const { icons } = payload;
123
+ document.documentElement.dataset['statusBarIcons'] = icons;
124
+ return null;
125
+ });
126
+ darkSchemeQuery.addEventListener('change', () => {
127
+ host.emit(BridgeEvents.colorSchemeChanged, { colorScheme: currentColorScheme() });
128
+ });
129
+ window.addEventListener('resize', () => {
130
+ host.emit(BridgeEvents.viewportChanged, {
131
+ safeAreaInsets: MOCK_SAFE_AREA,
132
+ capsule: MOCK_CAPSULE,
133
+ screenWidth: window.innerWidth,
134
+ screenHeight: window.innerHeight,
135
+ });
136
+ });
137
+ host.handle(BridgeMethods.navPush, () => null);
138
+ host.handle(BridgeMethods.navPop, () => null);
139
+ host.handle(BridgeMethods.navReplace, () => null);
140
+ host.handle(BridgeMethods.navReset, () => null);
141
+ host.handle(BridgeMethods.navSwitchTab, () => null);
142
+ host.handle(BridgeMethods.appReportError, (payload) => {
143
+ const { source, message, stack } = payload;
144
+ console.error(`[cadence miniapp] ${source} — ${message}`, stack ?? '');
145
+ return null;
146
+ });
147
+ host.handle(BridgeMethods.navSetChrome, (payload) => {
148
+ document.title = payload.title;
149
+ return null;
150
+ });
151
+ document.addEventListener('keydown', (event) => {
152
+ if (event.key === 'Escape') {
153
+ host.emit(BridgeEvents.navBackRequest);
154
+ }
155
+ });
156
+ /* Un onglet masqué ne se regarde plus : le conteneur annonce de même
157
+ l'arrière-plan, un écran de l'hôte par-dessus ou la fermeture (ADR-030). */
158
+ document.addEventListener('visibilitychange', () => {
159
+ host.emit(document.hidden ? BridgeEvents.appHide : BridgeEvents.appShow);
160
+ });
161
+ function hideLoading() {
162
+ loadingOverlay?.remove();
163
+ loadingOverlay = null;
164
+ }
165
+ function makeDialogButton(label, color, onClick) {
166
+ const button = document.createElement('button');
167
+ button.textContent = label;
168
+ button.setAttribute('style', `flex:1;padding:13px;border:none;background:none;font-size:15px;font-weight:600;color:${color};cursor:pointer;`);
169
+ button.addEventListener('click', onClick);
170
+ return button;
171
+ }
172
+ function escapeHtml(text) {
173
+ return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
174
+ }
175
+ console.warn('[cadence dev] mock native host active — Échap simule le geste retour, un onglet masqué l’arrière-plan');
@@ -0,0 +1 @@
1
+ declare const events: EventSource;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ const events = new EventSource('/__cadence_dev');
3
+ events.addEventListener('reload', () => location.reload());
4
+ events.addEventListener('error', () => {
5
+ /* le serveur dev est parti ; EventSource retentera tout seul */
6
+ });
@@ -0,0 +1 @@
1
+ export {};