one 2.22.0 → 2.23.1

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 (109) hide show
  1. package/dist/cjs/fork/getPathFromState.cjs +2 -1
  2. package/dist/cjs/fork/getPathFromState.native.cjs +4 -1
  3. package/dist/cjs/fork/getPathFromState.native.js +4 -1
  4. package/dist/cjs/fork/getPathFromState.native.js.map +1 -1
  5. package/dist/cjs/platform/streams.cjs +17 -0
  6. package/dist/cjs/platform/streams.native.cjs +19 -0
  7. package/dist/cjs/platform/streams.native.js +21 -0
  8. package/dist/cjs/platform/streams.native.js.map +1 -0
  9. package/dist/cjs/routeTypes.cjs +17 -0
  10. package/dist/cjs/routeTypes.native.cjs +19 -0
  11. package/dist/cjs/routeTypes.native.js +21 -0
  12. package/dist/cjs/routeTypes.native.js.map +1 -0
  13. package/dist/cjs/router/router.cjs +1 -1
  14. package/dist/cjs/router/router.native.cjs +1 -1
  15. package/dist/cjs/router/router.native.js +1 -1
  16. package/dist/cjs/router/router.native.js.map +1 -1
  17. package/dist/cjs/vite/plugins/iosLinkSetPlugin.cjs +22 -6
  18. package/dist/cjs/vite/plugins/iosLinkSetPlugin.native.cjs +100 -25
  19. package/dist/cjs/vite/plugins/iosLinkSetPlugin.native.js +100 -25
  20. package/dist/cjs/vite/plugins/iosLinkSetPlugin.native.js.map +1 -1
  21. package/dist/cjs/vite/plugins/oneNativeMembers.cjs +288 -57
  22. package/dist/cjs/vite/plugins/oneNativeMembers.native.cjs +537 -169
  23. package/dist/cjs/vite/plugins/oneNativeMembers.native.js +537 -169
  24. package/dist/cjs/vite/plugins/oneNativeMembers.native.js.map +1 -1
  25. package/dist/esm/fork/getPathFromState.mjs +2 -1
  26. package/dist/esm/fork/getPathFromState.mjs.map +1 -1
  27. package/dist/esm/fork/getPathFromState.native.js +4 -1
  28. package/dist/esm/fork/getPathFromState.native.js.map +1 -1
  29. package/dist/esm/platform/streams.mjs +0 -0
  30. package/dist/esm/platform/streams.native.js +0 -0
  31. package/dist/esm/routeTypes.mjs +0 -0
  32. package/dist/esm/routeTypes.native.js +0 -0
  33. package/dist/esm/router/router.mjs +2 -2
  34. package/dist/esm/router/router.mjs.map +1 -1
  35. package/dist/esm/router/router.native.js +2 -2
  36. package/dist/esm/router/router.native.js.map +1 -1
  37. package/dist/esm/vite/plugins/iosLinkSetPlugin.mjs +22 -6
  38. package/dist/esm/vite/plugins/iosLinkSetPlugin.mjs.map +1 -1
  39. package/dist/esm/vite/plugins/iosLinkSetPlugin.native.js +100 -25
  40. package/dist/esm/vite/plugins/iosLinkSetPlugin.native.js.map +1 -1
  41. package/dist/esm/vite/plugins/oneNativeMembers.mjs +289 -58
  42. package/dist/esm/vite/plugins/oneNativeMembers.mjs.map +1 -1
  43. package/dist/esm/vite/plugins/oneNativeMembers.native.js +538 -170
  44. package/dist/esm/vite/plugins/oneNativeMembers.native.js.map +1 -1
  45. package/ios/OneNativeSlot.swift +17 -0
  46. package/package.json +13 -13
  47. package/src/Root.tsx +1 -1
  48. package/src/constants.ts +1 -1
  49. package/src/createApp.native.tsx +1 -1
  50. package/src/createApp.tsx +3 -2
  51. package/src/fork/getPathFromState.test.ts +20 -0
  52. package/src/fork/getPathFromState.ts +8 -2
  53. package/src/headless.tsx +1 -1
  54. package/src/interfaces/router.ts +3 -27
  55. package/src/platform/file-system/classes.native.ts +6 -5
  56. package/src/platform/file-system/classes.ts +6 -5
  57. package/src/platform/streams.ts +14 -0
  58. package/src/routeTypes.ts +83 -0
  59. package/src/router/FlagsContext.ts +1 -1
  60. package/src/router/Route.tsx +1 -1
  61. package/src/router/getRoutes.ts +1 -1
  62. package/src/router/linkToColdRoute.test.ts +61 -1
  63. package/src/router/matchers.ts +1 -1
  64. package/src/router/router.ts +3 -8
  65. package/src/router/useInitializeOneRouter.ts +1 -1
  66. package/src/router/useViteRoutes.tsx +1 -1
  67. package/src/router/warmState.ts +1 -1
  68. package/src/types.ts +1 -1
  69. package/src/useMatches.ts +1 -1
  70. package/src/vite/one-server-only.tsx +5 -2
  71. package/src/vite/plugins/iosLinkSetPlugin.ts +39 -6
  72. package/src/vite/plugins/oneNativeMembers.ts +417 -82
  73. package/src/vite/types.ts +12 -51
  74. package/types/Root.d.ts +1 -1
  75. package/types/config.d.ts +1 -2
  76. package/types/config.d.ts.map +1 -1
  77. package/types/constants.d.ts +1 -1
  78. package/types/createApp.d.ts +3 -2
  79. package/types/createApp.d.ts.map +1 -1
  80. package/types/daemon/server.d.ts +1 -1
  81. package/types/fork/getPathFromState.d.ts.map +1 -1
  82. package/types/headless.d.ts +1 -1
  83. package/types/interfaces/router.d.ts +3 -19
  84. package/types/interfaces/router.d.ts.map +1 -1
  85. package/types/platform/file-system/classes.d.ts +4 -3
  86. package/types/platform/file-system/classes.d.ts.map +1 -1
  87. package/types/platform/file-system/classes.native.d.ts +4 -3
  88. package/types/platform/file-system/classes.native.d.ts.map +1 -1
  89. package/types/platform/streams.d.ts +12 -0
  90. package/types/platform/streams.d.ts.map +1 -0
  91. package/types/routeTypes.d.ts +66 -0
  92. package/types/routeTypes.d.ts.map +1 -0
  93. package/types/router/FlagsContext.d.ts +1 -1
  94. package/types/router/Route.d.ts +1 -1
  95. package/types/router/getRoutes.d.ts +1 -1
  96. package/types/router/matchers.d.ts +1 -1
  97. package/types/router/router.d.ts +1 -1
  98. package/types/router/router.d.ts.map +1 -1
  99. package/types/router/useInitializeOneRouter.d.ts +1 -1
  100. package/types/router/useViteRoutes.d.ts +1 -1
  101. package/types/router/warmState.d.ts +1 -1
  102. package/types/types.d.ts +1 -1
  103. package/types/useMatches.d.ts +1 -1
  104. package/types/vite/one-server-only.d.ts +5 -3
  105. package/types/vite/one-server-only.d.ts.map +1 -1
  106. package/types/vite/plugins/oneNativeMembers.d.ts +1 -1
  107. package/types/vite/plugins/oneNativeMembers.d.ts.map +1 -1
  108. package/types/vite/types.d.ts +12 -49
  109. package/types/vite/types.d.ts.map +1 -1
@@ -1,4 +1,4 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { readFileSync, statSync } from 'node:fs'
2
2
  import { dirname, resolve } from 'node:path'
3
3
  import MagicString from 'magic-string'
4
4
  import { parseSync } from 'oxc-parser'
@@ -6,43 +6,197 @@ import { parseSync } from 'oxc-parser'
6
6
  type Node = { type: string; [key: string]: any }
7
7
  type Binding = { source: string; imported: string }
8
8
 
9
- export function nativeOneMembers(file: string) {
10
- const imports = new Map<string, Binding>()
11
- const values = new Map<string, Node>()
12
- const program = parseSync(file, readFileSync(file, 'utf8')).program as Node
13
- for (const statement of program.body) {
14
- const node =
15
- statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
16
- if (node?.type === 'ImportDeclaration') {
17
- for (const item of node.specifiers) {
18
- imports.set(item.local.name, {
19
- source: node.source.value.startsWith('.')
20
- ? resolve(dirname(file), node.source.value)
21
- : node.source.value,
22
- imported:
23
- item.type === 'ImportSpecifier'
24
- ? String(item.imported.name ?? item.imported.value)
25
- : item.type === 'ImportDefaultSpecifier'
26
- ? 'default'
27
- : '*',
28
- })
29
- }
30
- } else if (node?.type === 'VariableDeclaration') {
31
- for (const declaration of node.declarations)
32
- if (declaration.id.type === 'Identifier' && declaration.init)
33
- values.set(declaration.id.name, declaration.init)
9
+ type Module = {
10
+ path: string
11
+ imports: Map<string, Binding>
12
+ values: Map<string, Node>
13
+ exports: Map<string, string>
14
+ reexports: Map<string, Binding>
15
+ stars: string[]
16
+ }
17
+
18
+ // resolves `One.X.Y` reads in app code to direct imports of the module that defines
19
+ // them, following one's re-export barrels and frozen namespace objects across files, so
20
+ // the bundle graph of an app reaches only the namespaces it reads.
21
+ export function nativeOneMembers(file: string, platform = 'ios') {
22
+ const modules = new Map<string, Module | undefined>()
23
+ const load = (path: string) => {
24
+ if (modules.has(path)) return modules.get(path)
25
+ let code: string
26
+ try {
27
+ code = readFileSync(path, 'utf8')
28
+ } catch {
29
+ modules.set(path, undefined)
30
+ return
31
+ }
32
+ const module: Module = {
33
+ path,
34
+ imports: new Map(),
35
+ values: new Map(),
36
+ exports: new Map(),
37
+ reexports: new Map(),
38
+ stars: [],
39
+ }
40
+ modules.set(path, module)
41
+ const from = (specifier: string) => {
42
+ if (!specifier.startsWith('.')) return specifier
43
+ const base = resolve(dirname(path), specifier)
44
+ // extensionless specifiers resolve the way the native bundler picks files
45
+ return (
46
+ [
47
+ '',
48
+ `.${platform}.js`,
49
+ '.native.js',
50
+ '.js',
51
+ `/index.${platform}.js`,
52
+ '/index.native.js',
53
+ '/index.js',
54
+ ]
55
+ .map((suffix) => base + suffix)
56
+ .find((candidate) =>
57
+ statSync(candidate, { throwIfNoEntry: false })?.isFile()
58
+ ) ?? base
59
+ )
60
+ }
61
+ const name = (node: Node) => String(node.name ?? node.value)
62
+ for (const statement of (parseSync(path, code).program as Node).body) {
63
+ if (statement.type === 'ExportAllDeclaration') {
64
+ if (statement.exported)
65
+ module.reexports.set(name(statement.exported), {
66
+ source: from(statement.source.value),
67
+ imported: '*',
68
+ })
69
+ else module.stars.push(from(statement.source.value))
70
+ continue
71
+ }
72
+ if (statement.type === 'ExportNamedDeclaration') {
73
+ for (const item of statement.specifiers ?? []) {
74
+ if (statement.source)
75
+ module.reexports.set(name(item.exported), {
76
+ source: from(statement.source.value),
77
+ imported: name(item.local),
78
+ })
79
+ else module.exports.set(name(item.exported), name(item.local))
80
+ }
81
+ }
82
+ const node =
83
+ statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
84
+ if (node?.type === 'ImportDeclaration') {
85
+ for (const item of node.specifiers) {
86
+ module.imports.set(item.local.name, {
87
+ source: from(node.source.value),
88
+ imported:
89
+ item.type === 'ImportSpecifier'
90
+ ? name(item.imported)
91
+ : item.type === 'ImportDefaultSpecifier'
92
+ ? 'default'
93
+ : '*',
94
+ })
95
+ }
96
+ } else if (node?.type === 'VariableDeclaration') {
97
+ for (const declaration of node.declarations)
98
+ if (declaration.id.type === 'Identifier') {
99
+ if (declaration.init) module.values.set(declaration.id.name, declaration.init)
100
+ if (node !== statement)
101
+ module.exports.set(declaration.id.name, declaration.id.name)
102
+ }
103
+ } else if (node && node !== statement && node.id) {
104
+ module.exports.set(node.id.name, node.id.name)
105
+ }
34
106
  }
107
+ return module
108
+ }
109
+ // the binding of the file in one that defines export `name` of `source`, or undefined
110
+ // when that module provably lacks it. a re-export of a package stays at the file
111
+ // re-exporting it, since the app may not resolve that package itself.
112
+ const resolveExport = (
113
+ source: string,
114
+ name: string,
115
+ seen = new Set<string>()
116
+ ): Binding | undefined => {
117
+ const module = load(source)
118
+ if (!module || seen.has(source)) return
119
+ seen.add(source)
120
+ const here = { source, imported: name }
121
+ const follow = (binding: Binding) =>
122
+ !load(binding.source)
123
+ ? here
124
+ : binding.imported === '*'
125
+ ? binding
126
+ : (resolveExport(binding.source, binding.imported, seen) ?? here)
127
+ const reexport = module.reexports.get(name)
128
+ if (reexport) return follow(reexport)
129
+ const local = module.exports.get(name)
130
+ if (local !== undefined) {
131
+ const imported = module.imports.get(local)
132
+ return imported && !module.values.has(local) ? follow(imported) : here
133
+ }
134
+ for (const star of module.stars) {
135
+ if (!load(star)) return here
136
+ const found = resolveExport(star, name, seen)
137
+ if (found) return found
138
+ }
139
+ }
140
+ const bind = (imported: Binding) =>
141
+ !load(imported.source)
142
+ ? undefined
143
+ : imported.imported === '*'
144
+ ? imported
145
+ : (resolveExport(imported.source, imported.imported) ?? imported)
146
+ type Found = { binding: Binding; consumed: number; call?: boolean; suffix?: string[] }
147
+ // reads `path` off the value bound to `binding`, as deep as the defining modules show
148
+ const descend = (
149
+ binding: Binding,
150
+ path: string[],
151
+ consumed: number
152
+ ): Found | undefined => {
153
+ const target = load(binding.source)
154
+ if (!target || !path.length) return { binding, consumed }
155
+ if (binding.imported === '*') {
156
+ const inner = resolveExport(binding.source, path[0])
157
+ return inner && descend(inner, path.slice(1), consumed + 1)
158
+ }
159
+ const value = target.values.get(target.exports.get(binding.imported) ?? '')
160
+ const found = value && member(target, value, path, consumed)
161
+ if (found) return found
162
+ // an object literal holding path[0] after any spread reads it off the binding
163
+ const object =
164
+ value?.type === 'CallExpression' && value.callee.property?.name === 'freeze'
165
+ ? value.arguments[0]
166
+ : value
167
+ const index =
168
+ object?.type === 'ObjectExpression'
169
+ ? object.properties.findLastIndex(
170
+ (property: Node) =>
171
+ property.type === 'SpreadElement' ||
172
+ (!property.computed &&
173
+ (property.key.name ?? property.key.value) === path[0])
174
+ )
175
+ : -1
176
+ return index >= 0 && object.properties[index].type === 'Property'
177
+ ? { binding, consumed: consumed + 1, suffix: [path[0]] }
178
+ : { binding, consumed }
35
179
  }
36
180
  const member = (
181
+ module: Module,
37
182
  expression: Node,
38
183
  path: string[],
39
184
  consumed = 0
40
- ): { binding: Binding; consumed: number; call?: boolean } | undefined => {
185
+ ): Found | undefined => {
41
186
  if (expression.type === 'Identifier') {
42
- const binding = imports.get(expression.name)
43
- if (binding) return { binding, consumed }
44
- const value = values.get(expression.name)
45
- return value ? member(value, path, consumed) : undefined
187
+ const imported = module.imports.get(expression.name)
188
+ if (imported) {
189
+ const binding = bind(imported)
190
+ return binding && descend(binding, path, consumed)
191
+ }
192
+ const value = module.values.get(expression.name)
193
+ const found = value && member(module, value, path, consumed)
194
+ if (found || module.path === file) return found
195
+ // an exported local the walk can't see into is imported as it is
196
+ for (const [exported, local] of module.exports)
197
+ if (local === expression.name)
198
+ return { binding: { source: module.path, imported: exported }, consumed }
199
+ return
46
200
  }
47
201
  if (
48
202
  expression.type === 'CallExpression' &&
@@ -50,7 +204,42 @@ export function nativeOneMembers(file: string) {
50
204
  expression.callee.object.name === 'Object' &&
51
205
  expression.callee.property.name === 'freeze'
52
206
  )
53
- return member(expression.arguments[0], path, consumed)
207
+ return member(module, expression.arguments[0], path, consumed)
208
+ if (expression.type === 'MemberExpression' && !expression.computed) {
209
+ const found = member(
210
+ module,
211
+ expression.object,
212
+ [expression.property.name, ...path],
213
+ consumed - 1
214
+ )
215
+ if (!found || found.consumed >= consumed) return found
216
+ // `Open.openSettings` of a local the module doesn't export reads off `Open`
217
+ if (found.call || found.consumed < consumed - 1) return
218
+ return {
219
+ ...found,
220
+ consumed,
221
+ suffix: [...(found.suffix ?? []), expression.property.name],
222
+ }
223
+ }
224
+ if (expression.type === 'ConditionalExpression') {
225
+ const test = expression.test
226
+ if (
227
+ test.type === 'BinaryExpression' &&
228
+ test.left.type === 'MemberExpression' &&
229
+ test.left.property.name === 'OS' &&
230
+ typeof test.right.value === 'string' &&
231
+ ['===', '!=='].includes(test.operator)
232
+ )
233
+ return member(
234
+ module,
235
+ (test.right.value === platform) === (test.operator === '===')
236
+ ? expression.consequent
237
+ : expression.alternate,
238
+ path,
239
+ consumed
240
+ )
241
+ return
242
+ }
54
243
  if (expression.type !== 'ObjectExpression' || !path.length) return
55
244
  for (const property of expression.properties.toReversed()) {
56
245
  if (
@@ -59,7 +248,7 @@ export function nativeOneMembers(file: string) {
59
248
  (property.key.name ?? property.key.value) === path[0]
60
249
  ) {
61
250
  if (property.kind === 'init')
62
- return member(property.value, path.slice(1), consumed + 1)
251
+ return member(module, property.value, path.slice(1), consumed + 1)
63
252
  const body = property.value.body.body
64
253
  const returned =
65
254
  body.length === 1 && body[0].type === 'ReturnStatement'
@@ -71,37 +260,99 @@ export function nativeOneMembers(file: string) {
71
260
  returned.callee.type === 'Identifier' &&
72
261
  !returned.arguments.length
73
262
  ) {
74
- const binding = imports.get(returned.callee.name)
263
+ const imported = module.imports.get(returned.callee.name)
264
+ const binding = imported && bind(imported)
75
265
  if (binding) return { binding, consumed: consumed + 1, call: true }
76
266
  }
77
267
  return
78
268
  }
269
+ // a spread provides path[0] only when its value is shown to hold it
79
270
  if (property.type === 'SpreadElement') {
80
- const found = member(property.argument, path, consumed)
81
- if (found) return found
271
+ const found = member(module, property.argument, path, consumed)
272
+ if (found && found.consumed > consumed) return found
82
273
  }
83
274
  }
84
275
  }
85
- return (source: string, id: string) => {
276
+ const shared = load(file)!
277
+ const one = shared.values.get('One')!
278
+ // `escape` hears of every read of `One` the rewrite leaves in place, which keeps the
279
+ // whole of one's platform barrel reachable from the module
280
+ return (source: string, id: string, escape: (reason: string) => void = () => {}) => {
281
+ if (
282
+ /\b(require|import)\s*\(\s*["'`]one["'`]\s*\)/.test(source) ||
283
+ /export\s*(\*(\s*as\s+[\w$]+)?|\{[^}]*\bOne\b[^}]*\})\s*from\s*["']one["']/.test(
284
+ source
285
+ )
286
+ )
287
+ escape('dynamic or re-exported one')
86
288
  const parsed = parseSync(id, source, {
87
289
  lang: /\.tsx$/.test(id) ? 'tsx' : /\.[cm]?ts$/.test(id) ? 'ts' : 'jsx',
88
290
  })
89
- if (parsed.errors.length) return
291
+ if (parsed.errors.length) {
292
+ escape('parse error')
293
+ return
294
+ }
90
295
  const app = parsed.program as Node
91
- const roots = new Map<string, string[]>()
296
+ // `name.<prefix>.rest` reads `One.<base>.rest`
297
+ const roots = new Map<string, { prefix: string[]; base: string[] }>()
92
298
  for (const node of app.body) {
93
- if (node.type !== 'ImportDeclaration' || node.source.value !== 'one') continue
299
+ if (
300
+ node.type !== 'ImportDeclaration' ||
301
+ node.source.value !== 'one' ||
302
+ node.importKind === 'type'
303
+ )
304
+ continue
94
305
  for (const item of node.specifiers) {
95
306
  if (
96
307
  item.type === 'ImportSpecifier' &&
308
+ item.importKind !== 'type' &&
97
309
  (item.imported.name ?? item.imported.value) === 'One'
98
310
  )
99
- roots.set(item.local.name, [])
311
+ roots.set(item.local.name, { prefix: [], base: [] })
100
312
  else if (item.type === 'ImportNamespaceSpecifier')
101
- roots.set(item.local.name, ['One'])
313
+ roots.set(item.local.name, { prefix: ['One'], base: [] })
102
314
  }
103
315
  }
104
316
  if (!roots.size) return
317
+ const chain = (node: Node) => {
318
+ const path: string[] = []
319
+ const nodes: Node[] = []
320
+ let root = node
321
+ while (
322
+ (root.type === 'MemberExpression' && !root.computed) ||
323
+ root.type === 'JSXMemberExpression'
324
+ ) {
325
+ path.unshift(root.property.name)
326
+ nodes.unshift(root)
327
+ root = root.object
328
+ }
329
+ const read = roots.get(root.name)
330
+ return {
331
+ root,
332
+ path,
333
+ nodes,
334
+ read,
335
+ // a namespace import reading another export of one leaves `One` alone
336
+ onePath:
337
+ read && read.prefix.every((name, index) => path[index] === name)
338
+ ? [...read.base, ...path.slice(read.prefix.length)]
339
+ : undefined,
340
+ }
341
+ }
342
+ // a module-level `const Swift = One.iOS` naming an object the rewrite can't import
343
+ // whole reads like One itself
344
+ const aliases = new Set<Node>()
345
+ for (const statement of app.body) {
346
+ if (statement.type !== 'VariableDeclaration' || statement.kind !== 'const') continue
347
+ for (const declaration of statement.declarations) {
348
+ if (declaration.id.type !== 'Identifier' || !declaration.init) continue
349
+ const { onePath } = chain(declaration.init)
350
+ if (!onePath?.length) continue
351
+ if (member(shared, one, onePath)?.consumed === onePath.length) continue
352
+ roots.set(declaration.id.name, { prefix: [], base: onePath })
353
+ aliases.add(declaration)
354
+ }
355
+ }
105
356
  const children = (node: Node, visit: (node: Node) => void) => {
106
357
  for (const [key, value] of Object.entries(node)) {
107
358
  if (
@@ -119,11 +370,15 @@ export function nativeOneMembers(file: string) {
119
370
  const pattern = (node: Node) => {
120
371
  if (node.type === 'Identifier') roots.delete(node.name)
121
372
  else if (node.type === 'Property') pattern(node.value)
122
- else children(node, pattern)
373
+ else if (node.type === 'AssignmentPattern') pattern(node.left)
374
+ else if (node.type === 'RestElement') pattern(node.argument)
375
+ else if (node.type === 'TSParameterProperty') pattern(node.parameter)
376
+ else if (node.type === 'ArrayPattern' || node.type === 'ObjectPattern')
377
+ children(node, pattern)
123
378
  }
124
379
  const shadows = (node: Node) => {
125
380
  if (node.type === 'ImportDeclaration') return
126
- if (node.type === 'VariableDeclarator') pattern(node.id)
381
+ if (node.type === 'VariableDeclarator' && !aliases.has(node)) pattern(node.id)
127
382
  if (
128
383
  node.type === 'FunctionDeclaration' ||
129
384
  node.type === 'FunctionExpression' ||
@@ -138,68 +393,148 @@ export function nativeOneMembers(file: string) {
138
393
  if (node.type === 'CatchClause' && node.param) pattern(node.param)
139
394
  children(node, shadows)
140
395
  }
396
+ const imported = roots.size
141
397
  shadows(app)
398
+ if (roots.size < imported) escape('shadowed One')
142
399
  const output = new MagicString(source)
143
- const added = new Map<Binding, string>()
400
+ const added = new Map<string, { binding: Binding; alias: string }>()
401
+ const rootOf = (node: Node): Node =>
402
+ node.type === 'MemberExpression' ? rootOf(node.object) : node
403
+ const escaped = new Set<string>()
404
+ const kept = (name: string, reason: string) => {
405
+ escaped.add(name)
406
+ escape(reason)
407
+ }
408
+ const typeOnly = (node: Node) =>
409
+ node.declare ||
410
+ node.type === 'TSTypeAliasDeclaration' ||
411
+ node.type === 'TSInterfaceDeclaration' ||
412
+ node.type === 'TSDeclareFunction' ||
413
+ (node.type.startsWith('TS') && node.type.endsWith('Type'))
414
+ let rewritten = 0
144
415
  const visit = (node: Node) => {
145
- if (node.type === 'ImportDeclaration' || node.type.startsWith('TS')) return
146
- if (node.type === 'AssignmentExpression') {
147
- visit(node.right)
416
+ if (node.type === 'ImportDeclaration' || aliases.has(node) || typeOnly(node)) return
417
+ if (node.type === 'Identifier') {
418
+ if (roots.has(node.name)) kept(node.name, `One read at ${node.start}`)
148
419
  return
149
420
  }
150
421
  if (
151
- node.type === 'UpdateExpression' ||
152
- (node.type === 'UnaryExpression' && node.operator === 'delete')
153
- )
422
+ (node.type === 'Property' ||
423
+ node.type === 'MethodDefinition' ||
424
+ node.type === 'PropertyDefinition') &&
425
+ !node.computed
426
+ ) {
427
+ if (node.value) visit(node.value)
154
428
  return
429
+ }
430
+ const target =
431
+ node.type === 'AssignmentExpression'
432
+ ? node.left
433
+ : node.type === 'UpdateExpression' ||
434
+ (node.type === 'UnaryExpression' && node.operator === 'delete')
435
+ ? node.argument
436
+ : undefined
437
+ if (target) {
438
+ if (roots.has(rootOf(target).name))
439
+ kept(rootOf(target).name, `One written at ${node.start}`)
440
+ if (node.type === 'AssignmentExpression') visit(node.right)
441
+ return
442
+ }
155
443
  if (node.type === 'MemberExpression' || node.type === 'JSXMemberExpression') {
156
- const path: string[] = []
157
- const nodes: Node[] = []
158
- let root = node
159
- while (
160
- (root.type === 'MemberExpression' && !root.computed) ||
161
- root.type === 'JSXMemberExpression'
162
- ) {
163
- path.unshift(root.property.name)
164
- nodes.unshift(root)
165
- root = root.object
166
- }
167
- const prefix = roots.get(root.name)
168
- if (prefix && prefix.every((name, index) => path[index] === name)) {
169
- const found = member(values.get('One')!, path.slice(prefix.length))
444
+ const { root, nodes, read, onePath } = chain(node)
445
+ if (read) {
446
+ if (!onePath) return
447
+ const found = member(shared, one, onePath)
448
+ const consumed = (found?.consumed ?? 0) - read.base.length
170
449
  if (
171
- found &&
172
- found.consumed &&
173
- !(found.call && node.type === 'JSXMemberExpression')
450
+ !found ||
451
+ consumed < 1 ||
452
+ (found.call && node.type === 'JSXMemberExpression')
174
453
  ) {
175
- let alias = added.get(found.binding)
176
- if (!alias) {
177
- alias = `__one_member_${added.size}`
178
- while (new RegExp(`\\b${alias}\\b`).test(source)) alias += '_'
179
- added.set(found.binding, alias)
180
- }
181
- output.overwrite(
182
- root.start,
183
- nodes[prefix.length + found.consumed - 1].end,
184
- found.call ? `(${alias}())` : alias
185
- )
454
+ kept(root.name, `One.${onePath.join('.')}`)
186
455
  return
187
456
  }
457
+ const key = `${found.binding.source}\0${found.binding.imported}`
458
+ let alias = added.get(key)?.alias
459
+ if (!alias) {
460
+ alias = `__one_member_${added.size}`
461
+ while (new RegExp(`\\b${alias}\\b`).test(source)) alias += '_'
462
+ added.set(key, { binding: found.binding, alias })
463
+ }
464
+ rewritten++
465
+ output.overwrite(
466
+ root.start,
467
+ nodes[read.prefix.length + consumed - 1].end,
468
+ found.call
469
+ ? `(${alias}())`
470
+ : alias + (found.suffix ?? []).map((name) => `.${name}`).join('')
471
+ )
472
+ return
473
+ }
474
+ if (nodes.length) {
475
+ visit(root)
476
+ return
188
477
  }
189
478
  }
190
479
  children(node, visit)
191
480
  }
192
481
  visit(app)
193
- if (!added.size) return
482
+ // every reference to a root must have been rewritten, whatever syntax holds it
483
+ let references = 0
484
+ const count = (node: Node) => {
485
+ if (node.type === 'ImportDeclaration' || aliases.has(node) || typeOnly(node)) return
486
+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
487
+ if (roots.has(node.name)) references++
488
+ return
489
+ }
490
+ if (node.type === 'MemberExpression' || node.type === 'JSXMemberExpression') {
491
+ count(node.object)
492
+ if (node.computed) count(node.property)
493
+ return
494
+ }
495
+ if (
496
+ (node.type === 'Property' ||
497
+ node.type === 'MethodDefinition' ||
498
+ node.type === 'PropertyDefinition' ||
499
+ node.type === 'JSXAttribute') &&
500
+ !node.computed
501
+ ) {
502
+ if (node.value) count(node.value)
503
+ return
504
+ }
505
+ if (
506
+ node.type === 'LabeledStatement' ||
507
+ node.type === 'BreakStatement' ||
508
+ node.type === 'ContinueStatement'
509
+ ) {
510
+ if (node.body) count(node.body)
511
+ return
512
+ }
513
+ if (node.type === 'ExportSpecifier') {
514
+ count(node.local)
515
+ return
516
+ }
517
+ children(node, count)
518
+ }
519
+ count(app)
520
+ const complete = references === rewritten && roots.size === imported
521
+ if (!complete) escape('One reference left unrewritten')
522
+ // an alias whose every read became an import no longer needs One
523
+ for (const declaration of [...aliases].toReversed()) {
524
+ if (complete && roots.has(declaration.id.name) && !escaped.has(declaration.id.name))
525
+ output.overwrite(declaration.init.start, declaration.init.end, 'void 0')
526
+ else escaped.add(chain(declaration.init).root.name)
527
+ }
528
+ if (!added.size && !aliases.size) return
194
529
  const lastImport = app.body
195
530
  .filter((node: Node) => node.type === 'ImportDeclaration')
196
531
  .at(-1)
197
532
  output.appendLeft(
198
533
  lastImport.end,
199
534
  '\n' +
200
- [...added]
535
+ [...added.values()]
201
536
  .map(
202
- ([binding, alias]) =>
537
+ ({ binding, alias }) =>
203
538
  `import ${binding.imported === '*' ? `* as ${alias}` : `{ ${binding.imported} as ${alias} }`} from ${JSON.stringify(binding.source)};\n`
204
539
  )
205
540
  .join('')