@tamagui/cli 1.74.4 → 1.74.6

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 (59) hide show
  1. package/dist/cli.js +0 -15
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.native.js +0 -15
  4. package/dist/cli.native.js.map +1 -1
  5. package/dist/dev.js +3 -3
  6. package/dist/dev.js.map +1 -1
  7. package/dist/dev.native.js +3 -3
  8. package/dist/dev.native.js.map +1 -1
  9. package/package.json +10 -39
  10. package/src/cli.ts +0 -18
  11. package/types/dev.d.ts.map +1 -1
  12. package/src/dev/clientInjectPlugin.ts +0 -112
  13. package/src/dev/createDevServer.ts +0 -250
  14. package/src/dev/types.ts +0 -1
  15. package/src/dev.ts +0 -520
  16. package/src/test.ts +0 -12
  17. package/src/utils/constants.ts +0 -1
  18. package/src/vendor/debugger-app/index.d.ts +0 -2
  19. package/src/vendor/debugger-app/index.js +0 -3
  20. package/src/vendor/debugger-app/public/index.html +0 -49
  21. package/src/vendor/debugger-app/src/assets/blue-icon.png +0 -0
  22. package/src/vendor/debugger-app/src/assets/gray-icon.png +0 -0
  23. package/src/vendor/debugger-app/src/assets/orange-icon.png +0 -0
  24. package/src/vendor/debugger-app/src/debuggerWorker.js +0 -84
  25. package/src/vendor/debugger-app/src/index.css +0 -37
  26. package/src/vendor/debugger-app/src/index.js +0 -199
  27. package/src/vendor/debugger-app/webpack.config.cjs +0 -73
  28. package/src/vendor/repack/dev-server/src/createServer.ts +0 -155
  29. package/src/vendor/repack/dev-server/src/img/favicon.ico +0 -0
  30. package/src/vendor/repack/dev-server/src/index.ts +0 -2
  31. package/src/vendor/repack/dev-server/src/plugins/api/apiPlugin.ts +0 -50
  32. package/src/vendor/repack/dev-server/src/plugins/api/index.ts +0 -1
  33. package/src/vendor/repack/dev-server/src/plugins/compiler/compilerPlugin.ts +0 -84
  34. package/src/vendor/repack/dev-server/src/plugins/compiler/index.ts +0 -2
  35. package/src/vendor/repack/dev-server/src/plugins/compiler/types.ts +0 -37
  36. package/src/vendor/repack/dev-server/src/plugins/devtools/devtoolsPlugin.ts +0 -107
  37. package/src/vendor/repack/dev-server/src/plugins/devtools/index.ts +0 -1
  38. package/src/vendor/repack/dev-server/src/plugins/favicon/faviconPlugin.ts +0 -14
  39. package/src/vendor/repack/dev-server/src/plugins/favicon/index.ts +0 -1
  40. package/src/vendor/repack/dev-server/src/plugins/multipart/index.ts +0 -2
  41. package/src/vendor/repack/dev-server/src/plugins/multipart/multipartPlugin.ts +0 -77
  42. package/src/vendor/repack/dev-server/src/plugins/multipart/types.ts +0 -13
  43. package/src/vendor/repack/dev-server/src/plugins/symbolicate/Symbolicator.ts +0 -233
  44. package/src/vendor/repack/dev-server/src/plugins/symbolicate/index.ts +0 -3
  45. package/src/vendor/repack/dev-server/src/plugins/symbolicate/sybmolicatePlugin.ts +0 -48
  46. package/src/vendor/repack/dev-server/src/plugins/symbolicate/types.ts +0 -71
  47. package/src/vendor/repack/dev-server/src/plugins/wss/WebSocketRouter.ts +0 -74
  48. package/src/vendor/repack/dev-server/src/plugins/wss/WebSocketServer.ts +0 -60
  49. package/src/vendor/repack/dev-server/src/plugins/wss/index.ts +0 -3
  50. package/src/vendor/repack/dev-server/src/plugins/wss/servers/HermesInspectorProxy.ts +0 -158
  51. package/src/vendor/repack/dev-server/src/plugins/wss/servers/WebSocketApiServer.ts +0 -69
  52. package/src/vendor/repack/dev-server/src/plugins/wss/servers/WebSocketDebuggerServer.ts +0 -134
  53. package/src/vendor/repack/dev-server/src/plugins/wss/servers/WebSocketDevClientServer.ts +0 -74
  54. package/src/vendor/repack/dev-server/src/plugins/wss/servers/WebSocketEventsServer.ts +0 -205
  55. package/src/vendor/repack/dev-server/src/plugins/wss/servers/WebSocketHMRServer.ts +0 -97
  56. package/src/vendor/repack/dev-server/src/plugins/wss/servers/WebSocketMessageServer.ts +0 -401
  57. package/src/vendor/repack/dev-server/src/plugins/wss/types.ts +0 -17
  58. package/src/vendor/repack/dev-server/src/plugins/wss/wssPlugin.ts +0 -73
  59. package/src/vendor/repack/dev-server/src/types.ts +0 -206
package/src/dev.ts DELETED
@@ -1,520 +0,0 @@
1
- import { readFile, writeFile } from 'fs/promises'
2
- import { dirname, join, relative } from 'path'
3
-
4
- import * as babel from '@babel/core'
5
- import { CLIResolvedOptions } from '@tamagui/types'
6
- import viteReactPlugin, {
7
- swcTransform,
8
- transformForBuild,
9
- } from '@tamagui/vite-native-swc'
10
- import { getVitePath, nativePlugin, tamaguiPlugin } from '@tamagui/vite-plugin'
11
- import react from '@vitejs/plugin-react-swc'
12
- import chalk from 'chalk'
13
- import { parse } from 'es-module-lexer'
14
- import { pathExists } from 'fs-extra'
15
- import { InlineConfig, build, createServer, resolveConfig } from 'vite'
16
-
17
- import { clientInjectionsPlugin } from './dev/clientInjectPlugin'
18
- import { createDevServer } from './dev/createDevServer'
19
- import { HMRListener } from './dev/types'
20
- import { registerDispose } from './utils'
21
-
22
- export const dev = async (options: CLIResolvedOptions) => {
23
- const { root } = options
24
-
25
- process.on('uncaughtException', (err) => {
26
- // biome-ignore lint/suspicious/noConsoleLog: <explanation>
27
- console.log(err?.message || err)
28
- })
29
-
30
- const packageRootDir = join(__dirname, '..')
31
-
32
- // react native port (it scans 19000 +5)
33
- const port = options.port || 8081
34
-
35
- const tamaguiVitePlugin = tamaguiPlugin({
36
- ...options.tamaguiOptions,
37
- })
38
-
39
- const plugins = [
40
- //
41
- tamaguiVitePlugin,
42
- ] satisfies InlineConfig['plugins']
43
-
44
- if (process.env.IS_TAMAGUI_DEV) {
45
- const inspect = require('vite-plugin-inspect')
46
- // @ts-ignore
47
- plugins.push(inspect())
48
- }
49
-
50
- const hmrListeners: HMRListener[] = []
51
- const hotUpdatedCJSFiles = new Map<string, string>()
52
-
53
- let serverConfig = {
54
- root,
55
- mode: 'development',
56
- clearScreen: false,
57
-
58
- resolve: {
59
- alias: {
60
- 'react-native': 'react-native-web',
61
- },
62
- },
63
-
64
- plugins: [
65
- ...plugins,
66
-
67
- react(),
68
-
69
- {
70
- name: 'tamagui-client-transform',
71
-
72
- async handleHotUpdate({ read, modules, file }) {
73
- try {
74
- if (!file.includes('/src/')) {
75
- return
76
- }
77
-
78
- const [module] = modules
79
- if (!module) return
80
-
81
- const id = module?.url || file.replace(root, '')
82
-
83
- const code = await read()
84
-
85
- // got a weird pre compiled file on startup
86
- if (code.startsWith(`'use strict';`)) return
87
-
88
- if (!code) {
89
- return
90
- }
91
-
92
- let source = code
93
-
94
- // we have to remove jsx before we can parse imports...
95
- source = (await transformForBuild(id, source))?.code || ''
96
-
97
- const importsMap = {}
98
-
99
- // parse imports of modules into ids:
100
- // eg `import x from '@tamagui/core'` => `import x from '/me/node_modules/@tamagui/core/index.js'`
101
- const [imports] = parse(source)
102
-
103
- let accumulatedSliceOffset = 0
104
-
105
- for (const specifier of imports) {
106
- const { n: importName, s: start } = specifier
107
-
108
- if (importName) {
109
- const id = await getVitePath(file, importName)
110
- if (!id) {
111
- console.warn('???')
112
- continue
113
- }
114
-
115
- importsMap[id] = id.replace(/^(\.\.\/)+/, '')
116
-
117
- // replace module name with id for hmr
118
- const len = importName.length
119
- const extraLen = id.length - len
120
- source =
121
- source.slice(0, start + accumulatedSliceOffset) +
122
- id +
123
- source.slice(start + accumulatedSliceOffset + len)
124
- accumulatedSliceOffset += extraLen
125
- }
126
- }
127
-
128
- // then we have to convert to commonjs..
129
- source =
130
- (
131
- await swcTransform(id, source, {
132
- mode: 'serve-cjs',
133
- })
134
- )?.code || ''
135
-
136
- if (!source) {
137
- throw '❌ no source'
138
- }
139
-
140
- const hotUpdateSource = `exports = ((exports) => {
141
- const require = createRequire(${JSON.stringify(importsMap, null, 2)})
142
- ${source
143
- .replace(`import.meta.hot.accept(() => {})`, ``)
144
- // replace import.meta.glob with empty array in hot reloads
145
- .replaceAll(
146
- /import.meta.glob\(.*\)/gi,
147
- `globalThis['__importMetaGlobbed'] || {}`
148
- )};
149
- return exports })({})`
150
-
151
- hotUpdatedCJSFiles.set(id, hotUpdateSource)
152
- } catch (err) {
153
- // biome-ignore lint/suspicious/noConsoleLog: <explanation>
154
- console.log(`Error processing hmr update:`, err)
155
- }
156
- },
157
- },
158
- ],
159
- server: {
160
- cors: true,
161
- port: options.port,
162
- host: options.host || '127.0.0.1',
163
- },
164
- } satisfies InlineConfig
165
-
166
- // first resolve config so we can pass into client plugin, then add client plugin:
167
- const resolvedConfig = await resolveConfig(serverConfig, 'serve')
168
-
169
- const viteRNClientPlugin = clientInjectionsPlugin(resolvedConfig)
170
-
171
- serverConfig = {
172
- ...serverConfig,
173
- plugins: [...serverConfig.plugins],
174
- }
175
-
176
- const server = await createServer(serverConfig)
177
-
178
- server.watcher.addListener('change', async (path) => {
179
- const id = path.replace(process.cwd(), '')
180
- if (!id.endsWith('tsx') && !id.endsWith('jsx')) {
181
- return
182
- }
183
- // just so it thinks its loaded
184
- try {
185
- void server.transformRequest(id)
186
- } catch (err) {
187
- // ok
188
- // biome-ignore lint/suspicious/noConsoleLog: <explanation>
189
- console.log('err', err)
190
- }
191
- })
192
-
193
- await server.listen()
194
-
195
- let isBuilding: Promise<string> | null = null
196
-
197
- const dispose = await createDevServer(options, {
198
- hotUpdatedCJSFiles,
199
- listenForHMR(cb) {
200
- hmrListeners.push(cb)
201
- },
202
- getIndexBundle: getBundleCode,
203
- indexJson: getIndexJsonReponse({ port, root }),
204
- })
205
-
206
- // biome-ignore lint/suspicious/noConsoleLog: ok
207
- console.log(`Listening on:`, chalk.green(`http://localhost:${port}`))
208
- server.printUrls()
209
-
210
- registerDispose(() => {
211
- dispose()
212
- server.close()
213
- })
214
-
215
- await new Promise((res) => server.httpServer?.on('close', res))
216
-
217
- async function getBundleCode() {
218
- // for easier quick testing things:
219
- const tmpBundle = join(process.cwd(), 'bundle.tmp.js')
220
- if (await pathExists(tmpBundle)) {
221
- // biome-ignore lint/suspicious/noConsoleLog: <explanation>
222
- console.log(
223
- '⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️ returning temp bundle ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️',
224
- tmpBundle
225
- )
226
- return await readFile(tmpBundle, 'utf-8')
227
- }
228
-
229
- if (isBuilding) {
230
- const res = await isBuilding
231
- return res
232
- }
233
-
234
- let done
235
- isBuilding = new Promise((res) => {
236
- done = res
237
- })
238
-
239
- const jsxRuntime = {
240
- alias: 'virtual:react-jsx',
241
- contents: await readFile(
242
- require.resolve('@tamagui/react-native-prebuilt/jsx-runtime'),
243
- 'utf-8'
244
- ),
245
- } as const
246
-
247
- const virtualModules = {
248
- 'react-native': {
249
- alias: 'virtual:react-native',
250
- contents: await readFile(
251
- require.resolve('@tamagui/react-native-prebuilt'),
252
- 'utf-8'
253
- ),
254
- },
255
- react: {
256
- alias: 'virtual:react',
257
- contents: await readFile(
258
- require.resolve('@tamagui/react-native-prebuilt/react'),
259
- 'utf-8'
260
- ),
261
- },
262
- 'react/jsx-runtime': jsxRuntime,
263
- 'react/jsx-dev-runtime': jsxRuntime,
264
- } as const
265
-
266
- const swapRnPlugin = {
267
- name: `swap-react-native`,
268
- enforce: 'pre',
269
-
270
- resolveId(id) {
271
- if (id.startsWith('react-native/Libraries')) {
272
- return `virtual:rn-internals:${id}`
273
- }
274
-
275
- for (const targetId in virtualModules) {
276
- if (id === targetId || id.includes(`node_modules/${targetId}/`)) {
277
- const info = virtualModules[targetId]
278
- return info.alias
279
- }
280
- }
281
- },
282
-
283
- load(id) {
284
- if (id.startsWith('virtual:rn-internals')) {
285
- const idOut = id.replace('virtual:rn-internals:', '')
286
- return `const val = __cachedModules["${idOut}"]
287
- export const PressabilityDebugView = val.PressabilityDebugView
288
- export default val ? val.default || val : val`
289
- }
290
-
291
- for (const targetId in virtualModules) {
292
- const info = virtualModules[targetId as keyof typeof virtualModules]
293
- if (id === info.alias) {
294
- return info.contents
295
- }
296
- }
297
- },
298
- } as const
299
-
300
- async function babelReanimated(input: string, filename: string) {
301
- return await new Promise<string>((res, rej) => {
302
- babel.transform(
303
- input,
304
- {
305
- plugins: ['react-native-reanimated/plugin'],
306
- filename,
307
- },
308
- (err: any, result) => {
309
- if (!result || err) rej(err || 'no res')
310
- res(result!.code!)
311
- }
312
- )
313
- })
314
- }
315
-
316
- // build app
317
- const buildConfig = {
318
- plugins: [
319
- swapRnPlugin,
320
-
321
- tamaguiPlugin({
322
- disableWatchTamaguiConfig: true,
323
- ...options.tamaguiOptions,
324
- platform: 'native',
325
- }),
326
-
327
- // needs to run before resolve... smh
328
- // {
329
- // name: `react-native-screens`,
330
- // enforce: 'pre',
331
-
332
- // async transform(code, id) {
333
- // if (id.includes('react-native-screens') && id.endsWith('.index.native.js')) {
334
- // const cjsExport = /exports\.([a-z0-9]+) = (.*)\n/gi
335
-
336
- // const out = code
337
- // .split('\n')
338
- // .map((line) => {
339
- // const matched = line.match(cjsExport)
340
- // if (!matched) return line
341
- // return line.replace(
342
- // cjsExport,
343
- // `
344
- // $1 = $2
345
- // export { $1 }
346
- // `
347
- // )
348
- // })
349
- // .join('\n')
350
-
351
- // console.log('now', out)
352
-
353
- // return out
354
- // }
355
- // },
356
- // },
357
-
358
- {
359
- name: 'reanimated',
360
-
361
- async transform(code, id) {
362
- if (code.includes('worklet')) {
363
- const out = await babelReanimated(code, id)
364
- return out
365
- }
366
- },
367
- },
368
-
369
- viteRNClientPlugin,
370
-
371
- nativePlugin({
372
- port,
373
- mode: 'build',
374
- }),
375
-
376
- viteReactPlugin({
377
- tsDecorators: true,
378
- mode: 'build',
379
- }),
380
- ],
381
- appType: 'custom',
382
- root,
383
- clearScreen: false,
384
-
385
- build: {
386
- ssr: false,
387
- minify: false,
388
- commonjsOptions: {
389
- transformMixedEsModules: true,
390
- },
391
- rollupOptions: {
392
- treeshake: false,
393
- preserveEntrySignatures: 'strict',
394
- output: {
395
- preserveModules: true,
396
- format: 'cjs',
397
- },
398
- },
399
- },
400
-
401
- mode: 'development',
402
- define: {
403
- 'process.env.NODE_ENV': `"development"`,
404
- },
405
- } satisfies InlineConfig
406
-
407
- // this fixes my swap-react-native plugin not being called pre 😳
408
- const resolvedConfig = await resolveConfig(buildConfig, 'build')
409
-
410
- const buildOutput = await build(buildConfig)
411
-
412
- if (!('output' in buildOutput)) {
413
- throw `❌`
414
- }
415
-
416
- let appCode = buildOutput.output
417
- // entry last
418
- .sort((a, b) => (a['isEntry'] ? 1 : -1))
419
- .map((module) => {
420
- if (module.type == 'chunk') {
421
- const importsMap = {}
422
- for (const imp of module.imports) {
423
- const relativePath = relative(dirname(module.fileName), imp)
424
- importsMap[relativePath[0] === '.' ? relativePath : './' + relativePath] = imp
425
- }
426
-
427
- return `
428
- ___modules___["${module.fileName}"] = ((exports, module) => {
429
- const require = createRequire(${JSON.stringify(importsMap, null, 2)})
430
-
431
- ${module.code}
432
- })
433
-
434
- ${
435
- module.isEntry
436
- ? `
437
- // run entry
438
- const __require = createRequire({})
439
- __require("react-native")
440
- __require("${module.fileName}")
441
- `
442
- : ''
443
- }
444
- `
445
- }
446
- })
447
- .join('\n')
448
-
449
- if (!appCode) {
450
- throw `❌`
451
- }
452
-
453
- appCode = appCode
454
- // this can be done in the individual file transform
455
- .replaceAll('undefined.accept(() => {})', '')
456
- .replaceAll('undefined.accept(function() {});', '') // swc
457
-
458
- const templateFile = join(packageRootDir, 'react-native-template.js')
459
-
460
- const out = (await readFile(templateFile, 'utf-8')) + appCode
461
-
462
- void writeFile(join(process.cwd(), '.tamagui', 'bundle.js'), out, 'utf-8')
463
-
464
- done(out)
465
- isBuilding = null
466
-
467
- return out
468
- }
469
- }
470
-
471
- function getIndexJsonReponse({ port, root }: { port: number | string; root }) {
472
- return {
473
- name: 'myapp',
474
- slug: 'myapp',
475
- scheme: 'myapp',
476
- version: '1.0.0',
477
- jsEngine: 'jsc',
478
- orientation: 'portrait',
479
- icon: './assets/icon.png',
480
- userInterfaceStyle: 'light',
481
- splash: {
482
- image: './assets/splash.png',
483
- resizeMode: 'contain',
484
- backgroundColor: '#ffffff',
485
- imageUrl: 'http://127.0.0.1:8081/assets/./assets/splash.png',
486
- },
487
- updates: { fallbackToCacheTimeout: 0 },
488
- assetBundlePatterns: ['**/*'],
489
- ios: { supportsTablet: true, bundleIdentifier: 'com.natew.myapp' },
490
- android: {
491
- package: 'com.tamagui.myapp',
492
- adaptiveIcon: {
493
- foregroundImage: './assets/adaptive-icon.png',
494
- backgroundColor: '#FFFFFF',
495
- foregroundImageUrl: 'http://127.0.0.1:8081/assets/./assets/adaptive-icon.png',
496
- },
497
- },
498
- web: { favicon: './assets/favicon.png' },
499
- extra: { eas: { projectId: '061b4470-78c7-4d6a-b850-8167fb0a3434' } },
500
- _internal: {
501
- isDebug: false,
502
- projectRoot: root,
503
- dynamicConfigPath: null,
504
- staticConfigPath: join(root, 'app.json'),
505
- packageJsonPath: join(root, 'package.json'),
506
- },
507
- sdkVersion: '47.0.0',
508
- platforms: ['ios', 'android', 'web'],
509
- iconUrl: `http://127.0.0.1:${port}/assets/./assets/icon.png`,
510
- debuggerHost: `127.0.0.1:${port}`,
511
- logUrl: `http://127.0.0.1:${port}/logs`,
512
- developer: { tool: 'expo-cli', projectRoot: root },
513
- packagerOpts: { dev: true },
514
- mainModuleName: 'index',
515
- __flipperHack: 'React Native packager is running',
516
- hostUri: `127.0.0.1:${port}`,
517
- bundleUrl: `http://127.0.0.1:${port}/index.bundle?platform=ios&dev=true&hot=false&lazy=true`,
518
- id: '@anonymous/myapp-473c4543-3c36-4786-9db1-c66a62ac9b78',
519
- }
520
- }
package/src/test.ts DELETED
@@ -1,12 +0,0 @@
1
- /* eslint-disable no-console */
2
- import { CLIResolvedOptions } from '@tamagui/types'
3
-
4
- export const test = async (options: CLIResolvedOptions) => {
5
- const { dev } = await import('./dev.js')
6
-
7
- // failing on startup "Tamagui error bundling components require() of ES Module"
8
-
9
- void dev(options)
10
-
11
- console.log('run tests')
12
- }
@@ -1 +0,0 @@
1
- export const DEFAULT_PORT = 8081
@@ -1,2 +0,0 @@
1
- const debuggerAppPath: string
2
- export default debuggerAppPath
@@ -1,3 +0,0 @@
1
- import { URL, fileURLToPath } from 'url';
2
-
3
- export default fileURLToPath(new URL('./dist', import.meta.url));
@@ -1,49 +0,0 @@
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" />
6
- <link rel="icon" href="data:;base64,iVBORw0KGgo=" />
7
- <title>React Native Debugger</title>
8
- </head>
9
- <body>
10
- <!-- <noscript>You need to enable JavaScript to run Learning Lab.</noscript>
11
- <div id="root"></div> -->
12
- <div class="content">
13
- <label for="dark">
14
- <input type="checkbox" id="dark" onclick="Page.toggleDarkTheme()" />
15
- Dark Theme
16
- </label>
17
- <label for="maintain-priority">
18
- <input
19
- type="checkbox"
20
- id="maintain-priority"
21
- onclick="Page.togglePriorityMaintenance()"
22
- />
23
- Maintain Priority
24
- </label>
25
- <p>
26
- React Native JS code runs as a web worker inside this tab.
27
- </p>
28
- <p>
29
- Press <kbd id="shortcut" class="shortcut">⌘⌥I</kbd> to open Developer
30
- Tools. Enable
31
- <a href="https://stackoverflow.com/a/17324511/232122" target="_blank"
32
- >Pause On Caught Exceptions</a
33
- >
34
- for a better debugging experience.
35
- </p>
36
- <p>
37
- You may also install
38
- <a href="https://www.npmjs.com/package/react-devtools" target="_blank"
39
- >the standalone version of React Developer Tools</a
40
- >
41
- to inspect the React component hierarchy, their props, and state.
42
- </p>
43
- <p>Status: <span id="status">Loading...</span></p>
44
- <button class="reload-btn" onclick="window.onReloadClicked()">
45
- Reload app
46
- </button>
47
- </div>
48
- </body>
49
- </html>
@@ -1,84 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
-
9
- /* global __fbBatchedBridge, importScripts */
10
- /* eslint no-unused-vars: 0 */
11
- /* eslint no-restricted-globals: 0 */
12
-
13
- onmessage = (function () {
14
- var visibilityState;
15
- var showVisibilityWarning = (function () {
16
- var hasWarned = false;
17
- return function () {
18
- // Wait until `YellowBox` gets initialized before displaying the warning.
19
- if (hasWarned || console.warn.toString().includes('[native code]')) {
20
- return;
21
- }
22
- hasWarned = true;
23
- console.warn(
24
- 'Remote debugger is in a background tab which may cause apps to ' +
25
- 'perform slowly. Fix this by foregrounding the tab (or opening it in ' +
26
- 'a separate window).'
27
- );
28
- };
29
- })();
30
-
31
- var messageHandlers = {
32
- executeApplicationScript: function (message, sendReply) {
33
- for (var key in message.inject) {
34
- self[key] = JSON.parse(message.inject[key]);
35
- }
36
- var error;
37
- try {
38
- importScripts(message.url);
39
- } catch (err) {
40
- error = err.message;
41
- }
42
- sendReply(null /* result */, error);
43
- },
44
- setDebuggerVisibility: function (message) {
45
- visibilityState = message.visibilityState;
46
- },
47
- };
48
-
49
- return function (message) {
50
- if (visibilityState === 'hidden') {
51
- showVisibilityWarning();
52
- }
53
-
54
- var object = message.data;
55
-
56
- var sendReply = function (result, error) {
57
- postMessage({ replyID: object.id, result: result, error: error });
58
- };
59
-
60
- var handler = messageHandlers[object.method];
61
- if (handler) {
62
- // Special cased handlers
63
- handler(object, sendReply);
64
- } else {
65
- // Other methods get called on the bridge
66
- var returnValue = [[], [], [], 0];
67
- var error;
68
- try {
69
- if (typeof __fbBatchedBridge === 'object') {
70
- returnValue = __fbBatchedBridge[object.method].apply(
71
- null,
72
- object.arguments
73
- );
74
- } else {
75
- error = 'Failed to call function, __fbBatchedBridge is undefined';
76
- }
77
- } catch (err) {
78
- error = err.message;
79
- } finally {
80
- sendReply(JSON.stringify(returnValue), error);
81
- }
82
- }
83
- };
84
- })();