react-native-audio-browser 0.2.0-next.10 → 0.2.0-next.11

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.
@@ -0,0 +1,237 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { describe, it, expect } from 'vitest'
4
+
5
+ /**
6
+ * Drift guard for `ios/Model/NitroTypeStubs.swift`.
7
+ *
8
+ * The generated Nitro Swift types are `typealias`es onto C++ structs
9
+ * (`margelo.nitro.audiobrowser.*`), so SwiftPM cannot compile them without the
10
+ * whole Nitro C++ core — which is why the SPM test target substitutes
11
+ * hand-written stubs behind `#if !canImport(NitroModules)`. The cost of that
12
+ * trick is that the stubs can disagree with the real types, and when they do
13
+ * `swift test` still passes while the app build breaks. That has already
14
+ * happened once (1d2edade, "restore the SPM test-stub build after the artwork
15
+ * variants change").
16
+ *
17
+ * Neither native CI job can catch it: the Swift job only ever sees the stubs,
18
+ * and the app build only ever sees the generated types. This test is the one
19
+ * place both files are readable at once, so the check lives here.
20
+ *
21
+ * The rule is subset-with-exact-types. A stub may declare FEWER properties than
22
+ * the real type — shared `ios/` sources can only use what the stub declares, so
23
+ * an omission is safe. What is not safe is a property the real type spells
24
+ * differently: `var id: String` against a generated `id: String?` compiles under
25
+ * test and fails to compile in the app.
26
+ */
27
+ const ROOT = process.cwd()
28
+ const STUBS = join(ROOT, 'ios', 'Model', 'NitroTypeStubs.swift')
29
+ const GENERATED = join(ROOT, 'nitrogen', 'generated', 'ios', 'swift')
30
+
31
+ /**
32
+ * Stubbed types with no generated counterpart, and why. Anything else missing
33
+ * from `nitrogen/generated/ios/swift/` is a stub for a type that no longer
34
+ * exists — the loudest kind of drift.
35
+ */
36
+ const NOT_GENERATED: Record<string, string> = {
37
+ // Nitro core type (`nitro::NullType`), shipped by NitroModules rather than
38
+ // emitted per-project, so there is no file of ours to compare against.
39
+ NullType: 'provided by NitroModules core'
40
+ }
41
+
42
+ type Struct = { kind: 'struct'; members: Map<string, string> }
43
+ type Enum = { kind: 'enum'; members: Map<string, string> }
44
+ type Shape = Struct | Enum
45
+
46
+ /** Splits a parameter/case list on top-level commas, ignoring `[]`, `()`, `<>`. */
47
+ function splitTopLevel(text: string): string[] {
48
+ const parts: string[] = []
49
+ let depth = 0
50
+ let current = ''
51
+ for (const char of text) {
52
+ if (char === '[' || char === '(' || char === '<') depth++
53
+ else if (char === ']' || char === ')' || char === '>') depth--
54
+ if (char === ',' && depth === 0) {
55
+ parts.push(current)
56
+ current = ''
57
+ } else current += char
58
+ }
59
+ if (current.trim()) parts.push(current)
60
+ return parts.map((part) => part.trim()).filter(Boolean)
61
+ }
62
+
63
+ /** `label: Type` → [label, Type]. Splits on the FIRST colon (`[String: String]`). */
64
+ function splitLabelled(part: string): [string, string] | null {
65
+ const colon = part.indexOf(':')
66
+ if (colon < 0) return null
67
+ const label = part.slice(0, colon).trim()
68
+ // A generated init can carry both an argument label and a parameter name
69
+ // (`for value: String`); the property name is the last word before the colon.
70
+ const name = label.split(/\s+/).pop()!
71
+ return [name, part.slice(colon + 1).trim()]
72
+ }
73
+
74
+ const DECL =
75
+ /^\s*(?:(?:public|@frozen|indirect|final)\s+)*(struct|enum)\s+([A-Za-z_]\w*)\s*(?::[^{]*)?\{/
76
+
77
+ /** Parses every top-level `struct`/`enum` in a Swift file into its member map. */
78
+ function parseSwiftDecls(source: string): Map<string, Shape> {
79
+ const shapes = new Map<string, Shape>()
80
+ const lines = source.split('\n')
81
+
82
+ for (let i = 0; i < lines.length; i++) {
83
+ const decl = DECL.exec(lines[i]!)
84
+ if (!decl) continue
85
+ const keyword = decl[1]!
86
+ const name = decl[2]!
87
+ const members = new Map<string, string>()
88
+ let depth = 1
89
+
90
+ for (let j = i + 1; j < lines.length && depth > 0; j++) {
91
+ const body = lines[j]!.replace(/\/\/.*$/, '')
92
+
93
+ if (depth === 1) {
94
+ // Stored property: `var name: Type`, but not a computed one (`{` after).
95
+ const prop =
96
+ /^\s*(?:public\s+)?var\s+([A-Za-z_]\w*)\s*:\s*([^={]+?)\s*(?:=|$)/.exec(
97
+ body
98
+ )
99
+ if (prop && !/\{\s*$/.test(body)) members.set(prop[1]!, prop[2]!.trim())
100
+
101
+ // `case a`, `case a(T)`, `case a, b`
102
+ const enumCase = /^\s*case\s+(.+)$/.exec(body)
103
+ if (enumCase && keyword === 'enum') {
104
+ for (const one of splitTopLevel(enumCase[1]!)) {
105
+ const withPayload = /^([A-Za-z_]\w*)\s*\((.*)\)$/.exec(one)
106
+ if (withPayload)
107
+ members.set(withPayload[1]!, withPayload[2]!.trim())
108
+ else if (/^[A-Za-z_]\w*$/.test(one)) members.set(one, '')
109
+ }
110
+ }
111
+ }
112
+
113
+ for (const char of body) {
114
+ if (char === '{') depth++
115
+ else if (char === '}') depth--
116
+ }
117
+ }
118
+
119
+ shapes.set(name, {
120
+ kind: keyword === 'struct' ? 'struct' : 'enum',
121
+ members
122
+ } as Shape)
123
+ }
124
+ return shapes
125
+ }
126
+
127
+ /**
128
+ * Reads the real shape of a generated type. Nitro emits three forms: a struct
129
+ * (memberwise `init`), a string-backed enum (`init?(fromString:)`), and a
130
+ * variant (a plain `enum` with `first`/`second`/… payload cases).
131
+ */
132
+ function parseGenerated(name: string): Shape | null {
133
+ let source: string
134
+ try {
135
+ source = readFileSync(join(GENERATED, `${name}.swift`), 'utf8')
136
+ } catch {
137
+ return null
138
+ }
139
+
140
+ // Variant enums are declared outright, so the generic parser sees them.
141
+ const declared = parseSwiftDecls(source).get(name)
142
+ if (declared && declared.members.size > 0) return declared
143
+
144
+ // String-backed enum. Read the case names off the `stringValue` switch, which
145
+ // spells them out (`case .get: return "GET"`), rather than deriving them from
146
+ // the JS values — nitrogen's casing rule is not ours to reimplement.
147
+ if (source.includes('var stringValue: String')) {
148
+ const members = new Map<string, string>()
149
+ for (const match of source.matchAll(/case\s+\.(\w+)\s*:/g))
150
+ members.set(match[1]!, '')
151
+ return { kind: 'enum', members }
152
+ }
153
+
154
+ const init = /^\s*init\((.*)\)\s*\{/m.exec(source)
155
+ if (init) {
156
+ const members = new Map<string, string>()
157
+ for (const part of splitTopLevel(init[1]!)) {
158
+ const labelled = splitLabelled(part)
159
+ if (labelled) members.set(labelled[0], labelled[1])
160
+ }
161
+ return { kind: 'struct', members }
162
+ }
163
+
164
+ return null
165
+ }
166
+
167
+ /**
168
+ * Sugared and desugared spellings are the same Swift type — nitrogen emits
169
+ * `Dictionary<String, String>` where the stubs write `[String: String]`.
170
+ */
171
+ function normalizeType(type: string): string {
172
+ let previous: string
173
+ let current = type.replace(/\s+/g, ' ').trim()
174
+ do {
175
+ previous = current
176
+ current = current
177
+ .replace(/\bDictionary<([^<>]+),\s*([^<>]+)>/g, '[$1: $2]')
178
+ .replace(/\bArray<([^<>]+)>/g, '[$1]')
179
+ .replace(/\bOptional<([^<>]+)>/g, '$1?')
180
+ } while (current !== previous)
181
+ return current
182
+ }
183
+
184
+ describe('NitroTypeStubs mirror the generated Nitro types', () => {
185
+ const stubs = parseSwiftDecls(readFileSync(STUBS, 'utf8'))
186
+
187
+ it('parses the stub file', () => {
188
+ // A parser that silently matches nothing would make every check below pass.
189
+ expect(stubs.size).toBeGreaterThan(20)
190
+ expect(stubs.get('Track')?.members.get('src')).toBe('String?')
191
+ })
192
+
193
+ it('stubs only types that Nitro actually generates', () => {
194
+ const orphans = [...stubs.keys()].filter(
195
+ (name) => !(name in NOT_GENERATED) && parseGenerated(name) == null
196
+ )
197
+ expect(
198
+ orphans,
199
+ `Stubbed with no generated counterpart in nitrogen/generated/ios/swift — the type was ` +
200
+ `renamed or removed from the Nitro spec, so the stub is standing in for nothing:\n` +
201
+ orphans.join('\n')
202
+ ).toEqual([])
203
+ })
204
+
205
+ it('declares every stubbed property with the generated type', () => {
206
+ const drift: string[] = []
207
+
208
+ for (const [name, stub] of stubs) {
209
+ if (name in NOT_GENERATED) continue
210
+ const real = parseGenerated(name)
211
+ if (real == null) continue // reported by the previous test
212
+
213
+ for (const [member, stubType] of stub.members) {
214
+ const realType = real.members.get(member)
215
+ const what = real.kind === 'enum' ? 'case' : 'property'
216
+ if (realType == null) {
217
+ drift.push(
218
+ `${name}.${member}: stub declares a ${what} the generated type does not have`
219
+ )
220
+ } else if (normalizeType(realType) !== normalizeType(stubType)) {
221
+ drift.push(
222
+ `${name}.${member}: stub \`${stubType || '(no payload)'}\`, ` +
223
+ `generated \`${realType || '(no payload)'}\``
224
+ )
225
+ }
226
+ }
227
+ }
228
+
229
+ expect(
230
+ drift,
231
+ `ios/Model/NitroTypeStubs.swift disagrees with nitrogen/generated/ios/swift. ` +
232
+ `\`swift test\` compiles against the stub and will not catch this; the app build ` +
233
+ `compiles against the generated type and will fail. Fix the stub to match:\n` +
234
+ drift.join('\n')
235
+ ).toEqual([])
236
+ })
237
+ })