catchword 0.0.0-stage → 1.0.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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +314 -2
  3. package/bin/catchword.js +8 -0
  4. package/bin/falcon.js +5 -0
  5. package/dist/cli/adb.d.ts +6 -0
  6. package/dist/cli/adb.js +52 -0
  7. package/dist/cli/audit.d.ts +4 -0
  8. package/dist/cli/audit.js +91 -0
  9. package/dist/cli/build.d.ts +13 -0
  10. package/dist/cli/build.js +139 -0
  11. package/dist/cli/clean.d.ts +1 -0
  12. package/dist/cli/clean.js +15 -0
  13. package/dist/cli/create.d.ts +4 -0
  14. package/dist/cli/create.js +60 -0
  15. package/dist/cli/dev.d.ts +10 -0
  16. package/dist/cli/dev.js +23 -0
  17. package/dist/cli/index.d.ts +3 -0
  18. package/dist/cli/index.js +243 -0
  19. package/dist/cli/native.d.ts +18 -0
  20. package/dist/cli/native.js +232 -0
  21. package/dist/cli/simulator.d.ts +8 -0
  22. package/dist/cli/simulator.js +77 -0
  23. package/dist/cli/upload.d.ts +9 -0
  24. package/dist/cli/upload.js +135 -0
  25. package/dist/cli/util.d.ts +8 -0
  26. package/dist/cli/util.js +43 -0
  27. package/dist/config.d.ts +17 -0
  28. package/dist/config.js +90 -0
  29. package/dist/index.d.ts +16 -0
  30. package/dist/index.js +51 -0
  31. package/dist/native/api.d.ts +46 -0
  32. package/dist/native/api.js +185 -0
  33. package/dist/native/build.d.ts +47 -0
  34. package/dist/native/build.js +407 -0
  35. package/dist/native/elf.d.ts +15 -0
  36. package/dist/native/elf.js +200 -0
  37. package/dist/native/types.d.ts +9 -0
  38. package/dist/native/types.js +91 -0
  39. package/dist/native/wsl.d.ts +7 -0
  40. package/dist/native/wsl.js +29 -0
  41. package/dist/plugin/app-entry.d.ts +6 -0
  42. package/dist/plugin/app-entry.js +115 -0
  43. package/dist/plugin/assets.d.ts +4 -0
  44. package/dist/plugin/assets.js +84 -0
  45. package/dist/plugin/config.d.ts +14 -0
  46. package/dist/plugin/config.js +80 -0
  47. package/dist/plugin/context.d.ts +58 -0
  48. package/dist/plugin/context.js +255 -0
  49. package/dist/plugin/fallback.d.ts +4 -0
  50. package/dist/plugin/fallback.js +81 -0
  51. package/dist/plugin/image-service.d.ts +17 -0
  52. package/dist/plugin/image-service.js +138 -0
  53. package/dist/plugin/jsapi.d.ts +6 -0
  54. package/dist/plugin/jsapi.js +82 -0
  55. package/dist/plugin/output.d.ts +4 -0
  56. package/dist/plugin/output.js +75 -0
  57. package/dist/plugin/preview.d.ts +34 -0
  58. package/dist/plugin/preview.js +459 -0
  59. package/dist/plugin/sanitize.d.ts +5 -0
  60. package/dist/plugin/sanitize.js +48 -0
  61. package/dist/plugin/security.d.ts +4 -0
  62. package/dist/plugin/security.js +18 -0
  63. package/dist/plugin/sfc.d.ts +6 -0
  64. package/dist/plugin/sfc.js +181 -0
  65. package/dist/plugin/shim.d.ts +4 -0
  66. package/dist/plugin/shim.js +68 -0
  67. package/dist/plugin/state.d.ts +31 -0
  68. package/dist/plugin/state.js +61 -0
  69. package/dist/plugin/string-table.d.ts +7 -0
  70. package/dist/plugin/string-table.js +324 -0
  71. package/dist/plugin/style.d.ts +15 -0
  72. package/dist/plugin/style.js +114 -0
  73. package/dist/plugin/template.d.ts +7 -0
  74. package/dist/plugin/template.js +39 -0
  75. package/dist/steps/manifest.d.ts +9 -0
  76. package/dist/steps/manifest.js +60 -0
  77. package/dist/steps/pack.d.ts +3 -0
  78. package/dist/steps/pack.js +46 -0
  79. package/dist/steps/qjsc.d.ts +9 -0
  80. package/dist/steps/qjsc.js +186 -0
  81. package/dist/steps/report.d.ts +2 -0
  82. package/dist/steps/report.js +50 -0
  83. package/dist/steps/security.d.ts +17 -0
  84. package/dist/steps/security.js +310 -0
  85. package/dist/types.d.ts +158 -0
  86. package/dist/types.js +1 -0
  87. package/dist/util/class-tokenize.d.ts +2 -0
  88. package/dist/util/class-tokenize.js +56 -0
  89. package/dist/util/component-name.d.ts +6 -0
  90. package/dist/util/component-name.js +120 -0
  91. package/dist/util/fs.d.ts +14 -0
  92. package/dist/util/fs.js +70 -0
  93. package/dist/util/imports.d.ts +2 -0
  94. package/dist/util/imports.js +173 -0
  95. package/dist/util/log.d.ts +8 -0
  96. package/dist/util/log.js +24 -0
  97. package/package.json +61 -4
  98. package/template/README.md +38 -0
  99. package/template/catchword.config.ts +18 -0
  100. package/template/native/CMakeLists.txt +33 -0
  101. package/template/native/README.md +34 -0
  102. package/template/native/api.override.json +7 -0
  103. package/template/native/include/jsapi_demo.h +10 -0
  104. package/template/native/lib/README.md +10 -0
  105. package/template/native/sdk/README.md +6 -0
  106. package/template/native/src/bridge.cpp +9 -0
  107. package/template/native/src/jsapi_demo.cpp +11 -0
  108. package/template/package.json +38 -0
  109. package/template/src/app.js +45 -0
  110. package/template/src/app.json +11 -0
  111. package/template/src/base-page.js +150 -0
  112. package/template/src/components/HelloWorld.vue +20 -0
  113. package/template/src/mocks/$jsapi.test.js +5 -0
  114. package/template/src/mocks/test-module.js +5 -0
  115. package/template/src/pages/index/index.vue +41 -0
  116. package/template/src/pages/page/page.vue +63 -0
  117. package/template/src/shims.d.ts +21 -0
  118. package/template/src/styles/base.less +23 -0
  119. package/template/src/styles/mixin.less +32 -0
  120. package/template/src/styles/var.less +15 -0
  121. package/template/tsconfig.json +14 -0
  122. package/vendor/README.md +16 -0
  123. package/vendor/falcon-styler/.jscsrc +31 -0
  124. package/vendor/falcon-styler/LICENSE +21 -0
  125. package/vendor/falcon-styler/README.md +124 -0
  126. package/vendor/falcon-styler/index.js +273 -0
  127. package/vendor/falcon-styler/lib/shorthand-parser.js +78 -0
  128. package/vendor/falcon-styler/lib/util.js +30 -0
  129. package/vendor/falcon-styler/lib/validator.js +846 -0
  130. package/vendor/falcon-styler/package.json +32 -0
  131. package/vendor/licenses/falcon-styler.LICENSE +21 -0
  132. package/vendor/licenses/weex-template-compiler.README.md +3 -0
  133. package/vendor/package.json +5 -0
  134. package/vendor/qjsc/SHA256SUMS +11 -0
  135. package/vendor/qjsc/bin/darwin/arm64/qjsc20200705 +0 -0
  136. package/vendor/qjsc/bin/darwin/x64/qjsc20200412 +0 -0
  137. package/vendor/qjsc/bin/darwin/x64/qjsc20200705 +0 -0
  138. package/vendor/qjsc/bin/darwin/x64/qjsc20200906 +0 -0
  139. package/vendor/qjsc/bin/darwin/x64/qjscbn20200412 +0 -0
  140. package/vendor/qjsc/bin/darwin/x64/qjscbn20200705 +0 -0
  141. package/vendor/qjsc/bin/darwin/x64/qjscbn20200906 +0 -0
  142. package/vendor/qjsc/bin/linux/qjsc20200705 +0 -0
  143. package/vendor/qjsc/bin/win32/libgcc_s_dw2-1.dll +0 -0
  144. package/vendor/qjsc/bin/win32/pthreadGC-3.dll +0 -0
  145. package/vendor/qjsc/bin/win32/qjsc20200705.exe +0 -0
  146. package/vendor/web/falcon-js-web.js +863 -0
  147. package/vendor/web/falcon-jsapi-web.js +479 -0
  148. package/vendor/web/falcon-vue-render.js +11323 -0
  149. package/vendor/web/falcon-web-boot.js +4 -0
  150. package/vendor/web/falcon-web-hud.js +119 -0
  151. package/vendor/web/falcon-web-style.js +235 -0
  152. package/vendor/web/vue.runtime.common.dev.js +8467 -0
  153. package/vendor/web/vue.runtime.common.js +5 -0
  154. package/vendor/weex-template-compiler/README.md +3 -0
  155. package/vendor/weex-template-compiler/build.js +4824 -0
  156. package/vendor/weex-template-compiler/index.js +17 -0
  157. package/vendor/weex-template-compiler/package.json +25 -0
@@ -0,0 +1,34 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { AppContext } from './context.js';
3
+ import type { DeviceProfile, FalconUserConfig } from '../types.js';
4
+ export interface PreviewProfile {
5
+ name: string;
6
+ logical: {
7
+ width: number;
8
+ height: number;
9
+ };
10
+ panel: DeviceProfile['panel'] | null;
11
+ dpr: number;
12
+ viewport: number | null;
13
+ fontMetrics: string;
14
+ stage: boolean;
15
+ stageScale: number | 'fit';
16
+ memory: {
17
+ totalMB?: number;
18
+ baselineMB?: number;
19
+ show?: boolean;
20
+ } | null;
21
+ }
22
+ export declare function prebundleWebRuntime(ctx: AppContext): Promise<void>;
23
+ export declare function resolveProfile(config: FalconUserConfig): PreviewProfile | null;
24
+ export declare function loadNativeContract(root: string, config: FalconUserConfig): {
25
+ modules: {
26
+ name: string;
27
+ methods: {
28
+ name: string;
29
+ async: boolean;
30
+ }[];
31
+ }[];
32
+ } | null;
33
+ export declare function previewPlugin(ctx: AppContext): Plugin;
34
+ export declare function devRuntimePlugin(ctx: AppContext): Plugin;
@@ -0,0 +1,459 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { build as esbuild } from 'esbuild';
4
+ import { normalizePath } from 'vite';
5
+ import { devRuntimePaths, VENDOR_DIR } from './config.js';
6
+ import { readApiFile, resolveNativePaths } from '../native/api.js';
7
+ import { ensureDir } from '../util/fs.js';
8
+ import { log } from '../util/log.js';
9
+ const VUE_CJS = path.join(VENDOR_DIR, 'web/vue.runtime.common.js');
10
+ const RENDERER_CJS = path.join(VENDOR_DIR, 'web/falcon-vue-render.js');
11
+ const JSFM_JS = path.join(VENDOR_DIR, 'web/falcon-js-web.js');
12
+ const JSAPI_JS = path.join(VENDOR_DIR, 'web/falcon-jsapi-web.js');
13
+ const WEB_STYLE_JS = path.join(VENDOR_DIR, 'web/falcon-web-style.js');
14
+ const WEB_HUD_JS = path.join(VENDOR_DIR, 'web/falcon-web-hud.js');
15
+ const WEB_BOOT_JS = path.join(VENDOR_DIR, 'web/falcon-web-boot.js');
16
+ export async function prebundleWebRuntime(ctx) {
17
+ const paths = devRuntimePaths(ctx);
18
+ ensureDir(paths.dir);
19
+ const vendorDir = VENDOR_DIR;
20
+ await esbuild({
21
+ stdin: {
22
+ contents: `import Vue from ${JSON.stringify(VUE_CJS)};
23
+ export default Vue;
24
+ export const version = Vue.version;`,
25
+ resolveDir: vendorDir,
26
+ loader: 'js'
27
+ },
28
+ bundle: true,
29
+ format: 'esm',
30
+ platform: 'browser',
31
+ target: 'es2020',
32
+ define: { 'process.env.NODE_ENV': '"development"', global: 'globalThis' },
33
+ outfile: paths.vue,
34
+ logLevel: 'silent'
35
+ });
36
+ await esbuild({
37
+ stdin: {
38
+ contents: `import weex from ${JSON.stringify(RENDERER_CJS)};
39
+ export default weex;`,
40
+ resolveDir: vendorDir,
41
+ loader: 'js'
42
+ },
43
+ bundle: true,
44
+ format: 'esm',
45
+ platform: 'browser',
46
+ target: 'es2020',
47
+ define: { 'process.env.NODE_ENV': '"development"', global: 'globalThis' },
48
+ outfile: paths.weex,
49
+ logLevel: 'silent'
50
+ });
51
+ }
52
+ function toFsUrl(file) {
53
+ return '/@fs/' + normalizePath(file).replace(/^\/+/, '');
54
+ }
55
+ export function resolveProfile(config) {
56
+ const device = config.device;
57
+ if (!device || !device.logical)
58
+ return null;
59
+ const preview = config.preview ?? {};
60
+ return {
61
+ name: device.name ?? 'device',
62
+ logical: device.logical,
63
+ panel: device.panel ?? null,
64
+ dpr: device.dpr ?? 1,
65
+ viewport: device.viewport ?? null,
66
+ fontMetrics: device.fontMetrics ?? 'dom',
67
+ stage: preview.stage !== false,
68
+ stageScale: preview.stageScale ?? 'fit',
69
+ memory: preview.memory ?? null
70
+ };
71
+ }
72
+ export function loadNativeContract(root, config) {
73
+ try {
74
+ const paths = resolveNativePaths(root, config);
75
+ if (!fs.existsSync(paths.apiFile))
76
+ return null;
77
+ const api = readApiFile(paths.apiFile);
78
+ return {
79
+ modules: api.modules.map((module) => ({
80
+ name: module.name,
81
+ methods: module.methods.map((method) => ({
82
+ name: method.name,
83
+ async: method.async
84
+ }))
85
+ }))
86
+ };
87
+ }
88
+ catch (error) {
89
+ log.warn(`读取原生契约失败: ${String(error)}`);
90
+ return null;
91
+ }
92
+ }
93
+ function nativeContractScript(contract) {
94
+ if (!contract)
95
+ return '';
96
+ return `<script>window.__FALCON_NATIVE_API__ = ${JSON.stringify(contract)};</script>
97
+ `;
98
+ }
99
+ function fetchProxyScript(ctx) {
100
+ if (ctx.config.preview?.proxy === false)
101
+ return '';
102
+ return '<script>window.__FALCON_FETCH_PROXY__ = "/__falcon_fetch";</script>';
103
+ }
104
+ function jsapiRuntimeScript(ctx) {
105
+ const replay = ctx.config.preview?.shell;
106
+ const replayScript = replay && Object.keys(replay).length
107
+ ? `<script>window.__FALCON_SHELL_REPLAY__ = ${JSON.stringify(replay)};</script>
108
+ `
109
+ : '';
110
+ const contract = loadNativeContract(ctx.root, ctx.config);
111
+ return `${replayScript}${nativeContractScript(contract)}<script src="/falcon-jsapi-web.js"></script>`;
112
+ }
113
+ function jsapiReportScript() {
114
+ return '<script>setTimeout(function () { if (window.__FALCON_JSAPI_REPORT__) window.__FALCON_JSAPI_REPORT__() }, 0);</script>';
115
+ }
116
+ const NAV_PATCH = `<script>(function () {
117
+ var fields = ["userAgent","appVersion","platform","vendor","vendorSub","language","languages","cookieEnabled","hardwareConcurrency","deviceMemory","product"]
118
+ var nav = window.navigator
119
+ for (var i = 0; i < fields.length; i++) {
120
+ var name = fields[i]
121
+ var owner = nav
122
+ while (owner) {
123
+ var desc = Object.getOwnPropertyDescriptor(owner, name)
124
+ if (desc) {
125
+ if (!desc.configurable) break
126
+ var box = { has: false, value: undefined }
127
+ try {
128
+ Object.defineProperty(owner, name, {
129
+ configurable: true,
130
+ get: function () {
131
+ if (box.has) return box.value
132
+ return desc.get ? desc.get.call(this) : desc.value
133
+ },
134
+ set: function (value) { box.has = true; box.value = value }
135
+ })
136
+ } catch (e) {}
137
+ break
138
+ }
139
+ owner = Object.getPrototypeOf(owner)
140
+ }
141
+ }
142
+ })();</script>`;
143
+ function profileScript(profile) {
144
+ const value = profile ? JSON.stringify(profile) : 'null';
145
+ return `<script>window.__FALCON_PROFILE__ = ${value};</script>`;
146
+ }
147
+ function plainShellHtml(ctx, profile) {
148
+ const paths = devRuntimePaths(ctx);
149
+ return `<!doctype html>
150
+ <html>
151
+ <head>
152
+ <meta charset="utf-8" />
153
+ <title>Falcon Preview</title>
154
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
155
+ <style>
156
+ html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
157
+ #main { width: 100%; height: 100%; position: relative; }
158
+ #main > iframe { position: absolute; left: 0; top: 0; width: 100%; height: 100%; border: 0; }
159
+ </style>
160
+ </head>
161
+ <body>
162
+ ${NAV_PATCH}
163
+ ${fetchProxyScript(ctx)}
164
+ ${profileScript(profile)}
165
+ <div id="main"></div>
166
+ ${jsapiRuntimeScript(ctx)}
167
+ <script src="/falcon-js-web.js"></script>
168
+ ${jsapiReportScript()}
169
+ <script type="module" src="${toFsUrl(paths.previewAppEntry)}"></script>
170
+ </body>
171
+ </html>`;
172
+ }
173
+ function stageShellHtml(ctx, profile) {
174
+ const paths = devRuntimePaths(ctx);
175
+ const w = profile.logical.width;
176
+ const h = profile.logical.height;
177
+ return `<!doctype html>
178
+ <html>
179
+ <head>
180
+ <meta charset="utf-8" />
181
+ <title>Falcon Preview</title>
182
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
183
+ <style>
184
+ html, body { width: 100%; height: 100%; margin: 0; padding: 0; background: #0b0b0d; overflow: hidden; }
185
+ #stage { position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
186
+ #wrap { position: relative; }
187
+ #label { position: absolute; left: 0; bottom: 100%; margin-bottom: 6px; font: 11px ui-monospace, Menlo, monospace; color: #5f5f6b; white-space: nowrap; }
188
+ #device { position: relative; width: ${w}px; height: ${h}px; background: #000; outline: 1px solid #26262b; box-shadow: 0 16px 64px rgba(0, 0, 0, 0.72); transform-origin: center center; overflow: hidden; }
189
+ #main { position: absolute; left: 0; top: 0; width: 100%; height: 100%; }
190
+ #main > iframe { position: absolute; left: 0; top: 0; width: 100%; height: 100%; border: 0; }
191
+ </style>
192
+ </head>
193
+ <body>
194
+ ${NAV_PATCH}
195
+ ${fetchProxyScript(ctx)}
196
+ ${profileScript(profile)}
197
+ <div id="stage"><div id="wrap"><div id="label"></div><div id="device"><div id="main"></div></div></div></div>
198
+ ${jsapiRuntimeScript(ctx)}
199
+ <script src="/falcon-js-web.js"></script>
200
+ ${jsapiReportScript()}
201
+ <script type="module" src="${toFsUrl(paths.previewAppEntry)}"></script>
202
+ <script>
203
+ (function () {
204
+ var P = window.__FALCON_PROFILE__;
205
+ if (!P || !P.logical) return;
206
+ var device = document.getElementById('device');
207
+ var label = document.getElementById('label');
208
+ if (label) {
209
+ var panel = P.panel
210
+ ? ' | ' + P.panel.width + 'x' + P.panel.height + '@' + (P.panel.rotation == null ? 0 : P.panel.rotation)
211
+ : '';
212
+ label.textContent = P.name + ' ' + P.logical.width + 'x' + P.logical.height + panel + ' dpr ' + P.dpr;
213
+ }
214
+ var fit = function () {
215
+ var pad = 40;
216
+ var room = Math.min(
217
+ (window.innerWidth - pad) / P.logical.width,
218
+ (window.innerHeight - pad) / P.logical.height
219
+ );
220
+ var scale = typeof P.stageScale === 'number' ? P.stageScale : Math.min(1, room);
221
+ if (!(scale > 0)) scale = 1;
222
+ device.style.transform = 'scale(' + scale + ')';
223
+ };
224
+ fit();
225
+ window.addEventListener('resize', fit);
226
+ })();
227
+ </script>
228
+ </body>
229
+ </html>`;
230
+ }
231
+ function pageHtml(ctx, page, profile) {
232
+ const paths = devRuntimePaths(ctx);
233
+ const contract = loadNativeContract(ctx.root, ctx.config);
234
+ return `<!doctype html>
235
+ <html>
236
+ <head>
237
+ <meta charset="utf-8" />
238
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
239
+ <style>html, body { width: 100%; height: 100%; margin: 0; padding: 0; }</style>
240
+ </head>
241
+ <body>
242
+ ${NAV_PATCH}
243
+ ${fetchProxyScript(ctx)}
244
+ ${profileScript(profile)}
245
+ ${nativeContractScript(contract)}
246
+ <div id="root"></div>
247
+ <script type="module" src="${toFsUrl(paths.pageEntry(page))}"></script>
248
+ </body>
249
+ </html>`;
250
+ }
251
+ function initCall(config) {
252
+ const viewport = config.device?.viewport;
253
+ return typeof viewport === 'number' && viewport > 0
254
+ ? `weex.init(Vue, ${viewport})`
255
+ : 'weex.init(Vue)';
256
+ }
257
+ function writePreviewEntries(ctx) {
258
+ const paths = devRuntimePaths(ctx);
259
+ ensureDir(paths.dir);
260
+ const init = initCall(ctx.config);
261
+ fs.copyFileSync(WEB_STYLE_JS, path.join(paths.dir, 'falcon-web-style.js'));
262
+ fs.copyFileSync(WEB_HUD_JS, path.join(paths.dir, 'falcon-web-hud.js'));
263
+ fs.copyFileSync(WEB_BOOT_JS, path.join(paths.dir, 'falcon-web-boot.js'));
264
+ fs.writeFileSync(paths.previewAppEntry, `import './falcon-web-boot.js'
265
+ import Vue from 'vue'
266
+ import weex from 'falcon-vue-render'
267
+ import App from 'virtual:falcon-app'
268
+ import appJson from ${JSON.stringify(path.join(ctx.srcDir, 'app.json'))}
269
+ import { installMemoryHud } from './falcon-web-hud.js'
270
+
271
+ ${init}
272
+ installMemoryHud()
273
+ $falcon._web_boot_app(App, appJson)
274
+ `);
275
+ for (const [page, rel] of Object.entries(ctx.appJson.pages)) {
276
+ const abs = ctx.resolveSource(rel);
277
+ fs.writeFileSync(paths.pageEntry(page), `import './falcon-web-boot.js'
278
+ import Vue from 'vue'
279
+ import weex from 'falcon-vue-render'
280
+ import PageClass from ${JSON.stringify(abs)}
281
+
282
+ ${init}
283
+ if (!window.$falcon) {
284
+ console.error('boot fail: 请通过 _preview.app.html 打开预览')
285
+ } else {
286
+ $falcon._web_boot_page(PageClass, Vue, window)
287
+ }
288
+ `);
289
+ }
290
+ }
291
+ function serveFile(res, file, type) {
292
+ if (!fs.existsSync(file)) {
293
+ res.statusCode = 404;
294
+ res.end('not found');
295
+ return;
296
+ }
297
+ res.setHeader('Content-Type', type);
298
+ fs.createReadStream(file).pipe(res);
299
+ }
300
+ export function previewPlugin(ctx) {
301
+ return {
302
+ name: 'falcon:preview',
303
+ apply: 'serve',
304
+ configureServer(server) {
305
+ writePreviewEntries(ctx);
306
+ const profile = resolveProfile(ctx.config);
307
+ if (profile) {
308
+ const panel = profile.panel
309
+ ? ` 面板=${profile.panel.width}x${profile.panel.height}`
310
+ : '';
311
+ log.info(`预览设备: ${profile.name} ${profile.logical.width}x${profile.logical.height}` +
312
+ ` dpr=${profile.dpr}${panel}` +
313
+ (profile.stage ? ' (定尺台架)' : ''));
314
+ }
315
+ if (ctx.config.preview?.proxy !== false) {
316
+ server.middlewares.use((req, res, next) => {
317
+ const rawUrl = String(req.url ?? '');
318
+ const prefix = '/__falcon_fetch';
319
+ if (rawUrl.indexOf(prefix) !== 0)
320
+ return next();
321
+ const qIndex = rawUrl.indexOf('?');
322
+ const search = qIndex >= 0 ? rawUrl.slice(qIndex + 1) : '';
323
+ let target = '';
324
+ for (const pair of search.split('&')) {
325
+ if (pair.indexOf('url=') === 0) {
326
+ try {
327
+ target = decodeURIComponent(pair.slice(4));
328
+ }
329
+ catch (error) {
330
+ target = pair.slice(4);
331
+ }
332
+ }
333
+ }
334
+ let extraHeaders = {};
335
+ for (const pair of search.split('&')) {
336
+ if (pair.indexOf('h=') === 0) {
337
+ try {
338
+ const parsed = JSON.parse(decodeURIComponent(pair.slice(2)));
339
+ if (parsed && typeof parsed === 'object') {
340
+ for (const [key, value] of Object.entries(parsed)) {
341
+ extraHeaders[String(key).toLowerCase()] = String(value);
342
+ }
343
+ }
344
+ }
345
+ catch (error) { }
346
+ }
347
+ }
348
+ const isHttp = target.indexOf('http://') === 0 || target.indexOf('https://') === 0;
349
+ if (!isHttp) {
350
+ res.statusCode = 400;
351
+ res.end('bad url: ' + target);
352
+ return;
353
+ }
354
+ const chunks = [];
355
+ req.on('data', (chunk) => chunks.push(chunk));
356
+ req.on('end', async () => {
357
+ try {
358
+ const upstream = await fetch(target, {
359
+ method: req.method ?? 'GET',
360
+ headers: {
361
+ ...(req.headers['content-type']
362
+ ? { 'content-type': String(req.headers['content-type']) }
363
+ : {}),
364
+ ...(req.headers['user-agent']
365
+ ? { 'user-agent': String(req.headers['user-agent']) }
366
+ : {}),
367
+ ...extraHeaders
368
+ },
369
+ body: req.method === 'GET' || req.method === 'HEAD'
370
+ ? undefined
371
+ : Buffer.concat(chunks)
372
+ });
373
+ const buffer = Buffer.from(await upstream.arrayBuffer());
374
+ res.statusCode = upstream.status;
375
+ res.setHeader('access-control-allow-origin', '*');
376
+ res.setHeader('content-type', upstream.headers.get('content-type') ?? 'application/octet-stream');
377
+ res.end(buffer);
378
+ }
379
+ catch (error) {
380
+ res.statusCode = 502;
381
+ res.setHeader('access-control-allow-origin', '*');
382
+ res.end(String(error.message ?? error));
383
+ }
384
+ });
385
+ });
386
+ }
387
+ server.middlewares.use('/falcon-jsapi-web.js', (_req, res) => serveFile(res, JSAPI_JS, 'text/javascript; charset=utf-8'));
388
+ server.middlewares.use('/falcon-js-web.js', (_req, res) => serveFile(res, JSFM_JS, 'text/javascript; charset=utf-8'));
389
+ server.middlewares.use('/__falcon/profile.json', (_req, res) => {
390
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
391
+ res.end(JSON.stringify(profile));
392
+ });
393
+ server.middlewares.use('/images', (req, res, next) => {
394
+ const rel = decodeURIComponent((req.url ?? '/').split('?')[0]).replace(/^\/+/, '');
395
+ const file = path.join(ctx.buildDir, 'images', rel);
396
+ if (!fs.existsSync(file))
397
+ return next();
398
+ serveFile(res, file, 'application/octet-stream');
399
+ });
400
+ server.middlewares.use('/assets', (req, res, next) => {
401
+ const rel = decodeURIComponent((req.url ?? '/').split('?')[0]).replace(/^\/+/, '');
402
+ const file = path.join(ctx.buildDir, 'assets', rel);
403
+ if (!fs.existsSync(file))
404
+ return next();
405
+ serveFile(res, file, 'application/octet-stream');
406
+ });
407
+ server.middlewares.use(async (req, res, next) => {
408
+ const url = (req.url ?? '/').split('?')[0];
409
+ let html = null;
410
+ if (url === '/' || url === '/_preview.app.html') {
411
+ html =
412
+ profile && profile.stage
413
+ ? stageShellHtml(ctx, profile)
414
+ : plainShellHtml(ctx, profile);
415
+ }
416
+ else {
417
+ const match = /^\/([^/]+)\.html$/.exec(url);
418
+ if (match &&
419
+ Object.prototype.hasOwnProperty.call(ctx.appJson.pages, match[1])) {
420
+ html = pageHtml(ctx, match[1], profile);
421
+ }
422
+ }
423
+ if (html === null)
424
+ return next();
425
+ try {
426
+ const transformed = await server.transformIndexHtml(url, html);
427
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
428
+ res.end(transformed);
429
+ }
430
+ catch (err) {
431
+ next(err);
432
+ }
433
+ });
434
+ const contract = loadNativeContract(ctx.root, ctx.config);
435
+ if (contract) {
436
+ const methods = contract.modules.reduce((n, m) => n + m.methods.length, 0);
437
+ log.info(`原生契约: ${contract.modules.length} 个模块 / ${methods} 个方法(来自 api.json)`);
438
+ }
439
+ server.watcher.add(ctx.srcDir);
440
+ log.info(`预览入口: http://localhost:${server.config.server.port}/_preview.app.html`);
441
+ }
442
+ };
443
+ }
444
+ export function devRuntimePlugin(ctx) {
445
+ let pending = null;
446
+ return {
447
+ name: 'falcon:dev-runtime',
448
+ apply: 'serve',
449
+ async buildStart() {
450
+ if (!pending) {
451
+ pending = (async () => {
452
+ log.step('预打包浏览器预览运行时 (Vue 2.6 + weex-vue-render)');
453
+ await prebundleWebRuntime(ctx);
454
+ })();
455
+ }
456
+ await pending;
457
+ }
458
+ };
459
+ }
@@ -0,0 +1,5 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { AppContext } from './context.js';
3
+ declare function stripComments(code: string): string;
4
+ export declare function sanitizePlugin(ctx: AppContext): Plugin;
5
+ export { stripComments };
@@ -0,0 +1,48 @@
1
+ import { parseSync } from 'oxc-parser';
2
+ const KEEP_LICENSE_RE = /(?:^|\s)(?:@license|@preserve|@copyright)\b/i;
3
+ function stripComments(code) {
4
+ if (!code.includes('//') && !code.includes('/*'))
5
+ return code;
6
+ let parsed;
7
+ try {
8
+ parsed = parseSync('chunk.js', code);
9
+ }
10
+ catch {
11
+ return code;
12
+ }
13
+ const comments = (parsed.comments ?? []).filter((comment) => typeof comment.start === 'number' &&
14
+ typeof comment.end === 'number' &&
15
+ comment.end > comment.start &&
16
+ !(comment.value ?? '').trimStart().startsWith('!') &&
17
+ !KEEP_LICENSE_RE.test(comment.value ?? ''));
18
+ if (comments.length === 0)
19
+ return code;
20
+ let output = '';
21
+ let cursor = 0;
22
+ for (const comment of comments) {
23
+ if (comment.start < cursor)
24
+ continue;
25
+ output += code.slice(cursor, comment.start);
26
+ output += code.slice(comment.start, comment.end).replace(/[^\n]/g, ' ');
27
+ cursor = comment.end;
28
+ }
29
+ output += code.slice(cursor);
30
+ return output;
31
+ }
32
+ export function sanitizePlugin(ctx) {
33
+ return {
34
+ name: 'falcon:strip-comments',
35
+ apply: 'build',
36
+ enforce: 'post',
37
+ renderChunk: {
38
+ order: 'post',
39
+ handler(code) {
40
+ if (ctx.options.minify)
41
+ return null;
42
+ const next = stripComments(code);
43
+ return next === code ? null : { code: next, map: null };
44
+ }
45
+ }
46
+ };
47
+ }
48
+ export { stripComments };
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { AppContext } from './context.js';
3
+ import type { BuildState } from './state.js';
4
+ export declare function securityPlugin(ctx: AppContext, state: BuildState): Plugin;
@@ -0,0 +1,18 @@
1
+ import { assertNoBuildPathLeak, assertNoSensitiveFiles, assertNoSourceMaps, assertNoSourcePathLeak, scanSecrets, warnNativeLeaks } from '../steps/security.js';
2
+ export function securityPlugin(ctx, state) {
3
+ return {
4
+ name: 'falcon:security',
5
+ apply: 'build',
6
+ enforce: 'post',
7
+ closeBundle() {
8
+ if (ctx.cliBuild)
9
+ return;
10
+ assertNoSourceMaps(ctx);
11
+ assertNoSensitiveFiles(ctx);
12
+ assertNoSourcePathLeak(ctx, state);
13
+ assertNoBuildPathLeak(ctx, state);
14
+ warnNativeLeaks(ctx);
15
+ scanSecrets(ctx, state);
16
+ }
17
+ };
18
+ }
@@ -0,0 +1,6 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { AppContext } from './context.js';
3
+ import type { BuildState } from './state.js';
4
+ export declare const SCRIPT_QUERY = "falcon-script";
5
+ export declare const STYLE_QUERY = "falcon-style";
6
+ export declare function sfcPlugin(ctx: AppContext, state: BuildState): Plugin;