File size: 4,698 Bytes
b450976
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import {execSync} from "child_process"
import fs from "fs"
import path from "path"

import {IOSConfig, type ConfigPlugin, withDangerousMod, withInfoPlist, withPodfile} from "expo/config-plugins"

import {type BluetoothSdkPluginProps} from "./index"
import {resolveAnalyticsProps} from "./analyticsProps"

const BLUETOOTH_SDK_EXPO_ADAPTER_ENV = "MENTRA_BLUETOOTH_SDK_INCLUDE_EXPO_ADAPTER"
const BLUETOOTH_SDK_EXPO_ADAPTER_LINE = `ENV['${BLUETOOTH_SDK_EXPO_ADAPTER_ENV}'] ||= '1'`
const INFO_ANALYTICS_DISABLED = "MentraBluetoothSdkAnalyticsDisabled"
export const INFO_ANALYTICS_ENVIRONMENT = "MentraBluetoothSdkAnalyticsEnvironment"
export const INFO_SDK_VERSION = "MentraBluetoothSdkVersion"
const STALE_INFO_POSTHOG_API_KEY = "MentraBluetoothSdkPostHogApiKey"
const STALE_INFO_POSTHOG_HOST = "MentraBluetoothSdkPostHogHost"
/** Lets iOS complete the SDK's pending reconnect, and deliver BLE events, while the app is suspended. */
export const IOS_BLUETOOTH_BACKGROUND_MODE = "bluetooth-central"

const ensureBluetoothSdkExpoAdapterPodEnv = (podfile: string): string => {
  if (podfile.includes(BLUETOOTH_SDK_EXPO_ADAPTER_ENV)) {
    return podfile
  }

  const insertion = [
    "  # Expo apps need the SDK's Expo module adapter so autolinking can register BluetoothSdk.",
    `  ${BLUETOOTH_SDK_EXPO_ADAPTER_LINE}`,
    "",
  ].join("\n")

  return podfile.replace(/(target\s+['"][^'"]+['"]\s+do\n)/, `$1${insertion}`)
}

const withXcodeEnvLocal: ConfigPlugin = (config) => {
  return withDangerousMod(config, [
    "ios",
    async (config) => {
      try {
        // Get node executable path
        const nodeExecutable = execSync("which node", {encoding: "utf-8"}).trim()

        // Path to .xcode.env.local
        const iosPath = path.join(config.modRequest.platformProjectRoot)
        const xcodeEnvLocalPath = path.join(iosPath, ".xcode.env.local")

        // Content to write
        const content = `export NODE_BINARY=${nodeExecutable}\n`

        // Write or append to .xcode.env.local
        if (fs.existsSync(xcodeEnvLocalPath)) {
          const existingContent = fs.readFileSync(xcodeEnvLocalPath, "utf-8")
          if (!existingContent.includes("NODE_BINARY")) {
            fs.appendFileSync(xcodeEnvLocalPath, content)
          }
        } else {
          fs.writeFileSync(xcodeEnvLocalPath, content)
        }
      } catch (error) {
        console.warn("Failed to create .xcode.env.local:", error)
      }

      return config
    },
  ])
}

export function applyBluetoothSdkInfoPlist(

  infoPlist: IOSConfig.InfoPlist,

  props: BluetoothSdkPluginProps | undefined,

): IOSConfig.InfoPlist {
  const packageJson = require("../../package.json") as {version?: unknown}
  const sdkVersion = typeof packageJson.version === "string" ? packageJson.version.trim() : ""
  if (!sdkVersion) {
    throw new Error("@mentra/bluetooth-sdk package.json is missing a version")
  }

  const analytics = resolveAnalyticsProps(props)

  delete infoPlist[INFO_ANALYTICS_DISABLED]
  delete infoPlist[INFO_ANALYTICS_ENVIRONMENT]
  delete infoPlist[STALE_INFO_POSTHOG_API_KEY]
  delete infoPlist[STALE_INFO_POSTHOG_HOST]

  infoPlist[INFO_SDK_VERSION] = sdkVersion

  // Merge, never replace: apps may also declare audio, location or other modes.
  const declaredModes = infoPlist.UIBackgroundModes
  if (declaredModes !== undefined && !Array.isArray(declaredModes)) {
    throw new Error("ios.infoPlist.UIBackgroundModes must be an array of background mode strings")
  }
  const backgroundModes: string[] = declaredModes ?? []
  if (!backgroundModes.includes(IOS_BLUETOOTH_BACKGROUND_MODE)) {
    infoPlist.UIBackgroundModes = [...backgroundModes, IOS_BLUETOOTH_BACKGROUND_MODE]
  }
  if (analytics.disabled !== undefined) {
    infoPlist[INFO_ANALYTICS_DISABLED] = analytics.disabled
  }
  if (analytics.environment !== undefined) {
    infoPlist[INFO_ANALYTICS_ENVIRONMENT] = analytics.environment
  }

  return infoPlist
}

function withBluetoothSdkInfoPlist(config: any, props: BluetoothSdkPluginProps | undefined) {
  return withInfoPlist(config, (config) => {
    config.modResults = applyBluetoothSdkInfoPlist(config.modResults, props)
    return config
  })
}

export const withIosConfiguration: ConfigPlugin<BluetoothSdkPluginProps> = (config, props) => {
  config = withPodfile(config, (config) => {
    config.modResults.contents = ensureBluetoothSdkExpoAdapterPodEnv(config.modResults.contents)
    return config
  })
  config = withBluetoothSdkInfoPlist(config, props)

  if (props?.node) {
    config = withXcodeEnvLocal(config)
  }
  return config
}