@atom.io/spa 0.0.8 → 0.0.9

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 (151) hide show
  1. package/README.md +169 -25
  2. package/README.mdx +62 -15
  3. package/dist/astro-application.d.ts +1 -1
  4. package/dist/astro-client.d.ts +1 -1
  5. package/dist/astro-client.d.ts.map +1 -1
  6. package/dist/astro-client.js +5 -4
  7. package/dist/astro-client.js.map +1 -1
  8. package/dist/astro-resumability-client.d.ts +1 -1
  9. package/dist/astro-server.js +4 -4
  10. package/dist/astro-server.js.map +1 -1
  11. package/dist/{astro-shared-83hxw7-M.js → astro-shared-DBwINQav.js} +2 -2
  12. package/dist/{astro-shared-83hxw7-M.js.map → astro-shared-DBwINQav.js.map} +1 -1
  13. package/dist/{astro-shared-DZp1x8RQ.d.ts → astro-shared-KxK9OUSj.d.ts} +2 -2
  14. package/dist/{astro-shared-DZp1x8RQ.d.ts.map → astro-shared-KxK9OUSj.d.ts.map} +1 -1
  15. package/dist/astro.d.ts +1 -1
  16. package/dist/astro.js +1 -1
  17. package/dist/{capabilities-DNcnGRv_.d.ts → capabilities-ChgSs6bp.d.ts} +34 -6
  18. package/dist/capabilities-ChgSs6bp.d.ts.map +1 -0
  19. package/dist/client.min.js +1 -1
  20. package/dist/core-DD2giR6E.js +451 -0
  21. package/dist/core-DD2giR6E.js.map +1 -0
  22. package/dist/development/astro-client.js +5 -4
  23. package/dist/development/astro-client.js.map +1 -1
  24. package/dist/development/astro-server.js +4 -4
  25. package/dist/development/astro-server.js.map +1 -1
  26. package/dist/development/{astro-shared-83hxw7-M.js → astro-shared-DBwINQav.js} +2 -2
  27. package/dist/development/{astro-shared-83hxw7-M.js.map → astro-shared-DBwINQav.js.map} +1 -1
  28. package/dist/development/astro.js +1 -1
  29. package/dist/development/core-DrUd8x25.js +465 -0
  30. package/dist/development/core-DrUd8x25.js.map +1 -0
  31. package/dist/development/{dom-DQ0M3rLL.js → dom-BRFv7FP_.js} +150 -35
  32. package/dist/development/dom-BRFv7FP_.js.map +1 -0
  33. package/dist/development/floating.js +2 -6
  34. package/dist/development/floating.js.map +1 -1
  35. package/dist/development/hot.js +164 -0
  36. package/dist/development/hot.js.map +1 -0
  37. package/dist/development/identity-DwB8MTM1.js +121 -0
  38. package/dist/development/identity-DwB8MTM1.js.map +1 -0
  39. package/dist/development/index.js +5 -5
  40. package/dist/development/jsx-runtime-BGDPK50B.js +49 -0
  41. package/dist/development/jsx-runtime-BGDPK50B.js.map +1 -0
  42. package/dist/development/jsx-runtime.js +1 -25
  43. package/dist/development/konva.js +12 -5
  44. package/dist/development/konva.js.map +1 -1
  45. package/dist/development/motion.js +3 -20
  46. package/dist/development/motion.js.map +1 -1
  47. package/dist/development/renderer.js +41 -40
  48. package/dist/development/renderer.js.map +1 -1
  49. package/dist/development/{server-renderer-DCLoMdOX.js → server-renderer-u1-c5PGd.js} +8 -18
  50. package/dist/development/server-renderer-u1-c5PGd.js.map +1 -0
  51. package/dist/development/server.js +1 -1
  52. package/dist/{src-Bme1kz2b.js → development/src-CB7ruwRs.js} +3 -3
  53. package/dist/development/src-CB7ruwRs.js.map +1 -0
  54. package/dist/development/three.js +20 -19
  55. package/dist/development/three.js.map +1 -1
  56. package/dist/development/vite-WUiz1ju6.js +545 -0
  57. package/dist/development/vite-WUiz1ju6.js.map +1 -0
  58. package/dist/development/vite.js +1 -1
  59. package/dist/{dom-D8g3roX9.js → dom--HZvmgqd.js} +139 -32
  60. package/dist/dom--HZvmgqd.js.map +1 -0
  61. package/dist/floating.d.ts +1 -1
  62. package/dist/floating.d.ts.map +1 -1
  63. package/dist/floating.js +2 -6
  64. package/dist/floating.js.map +1 -1
  65. package/dist/hot.d.ts +15 -0
  66. package/dist/hot.d.ts.map +1 -0
  67. package/dist/hot.js +19 -0
  68. package/dist/hot.js.map +1 -0
  69. package/dist/identity-oFU5p-Qj.js +121 -0
  70. package/dist/identity-oFU5p-Qj.js.map +1 -0
  71. package/dist/{index-BFnXIfOj.d.ts → index-DdA39aMv.d.ts} +4 -4
  72. package/dist/{index-BFnXIfOj.d.ts.map → index-DdA39aMv.d.ts.map} +1 -1
  73. package/dist/index.d.ts +4 -4
  74. package/dist/index.js +5 -5
  75. package/dist/jsx-runtime-BGDPK50B.js +49 -0
  76. package/dist/jsx-runtime-BGDPK50B.js.map +1 -0
  77. package/dist/{jsx-runtime-DQnpyT_g.d.ts → jsx-runtime-CCvcEosg.d.ts} +14 -9
  78. package/dist/jsx-runtime-CCvcEosg.d.ts.map +1 -0
  79. package/dist/jsx-runtime.d.ts +1 -1
  80. package/dist/jsx-runtime.js +1 -25
  81. package/dist/konva.d.ts +46 -9
  82. package/dist/konva.d.ts.map +1 -1
  83. package/dist/konva.js +12 -5
  84. package/dist/konva.js.map +1 -1
  85. package/dist/motion.d.ts +1 -1
  86. package/dist/motion.js +3 -20
  87. package/dist/motion.js.map +1 -1
  88. package/dist/renderer.d.ts +1 -1
  89. package/dist/renderer.d.ts.map +1 -1
  90. package/dist/renderer.js +39 -40
  91. package/dist/renderer.js.map +1 -1
  92. package/dist/{server-renderer-D0rsFL_-.js → server-renderer-BYFDmqnM.js} +8 -18
  93. package/dist/server-renderer-BYFDmqnM.js.map +1 -0
  94. package/dist/server.d.ts +1 -1
  95. package/dist/server.js +1 -1
  96. package/dist/size.json +12 -12
  97. package/dist/{development/src-DoQgCX-O.js → src-B2W_TA_X.js} +3 -3
  98. package/dist/src-B2W_TA_X.js.map +1 -0
  99. package/dist/three.d.ts +3 -3
  100. package/dist/three.d.ts.map +1 -1
  101. package/dist/three.js +20 -19
  102. package/dist/three.js.map +1 -1
  103. package/dist/vite-WUiz1ju6.js +545 -0
  104. package/dist/vite-WUiz1ju6.js.map +1 -0
  105. package/dist/vite.d.ts.map +1 -1
  106. package/dist/vite.js +1 -1
  107. package/package.json +16 -9
  108. package/src/astro-client.ts +3 -2
  109. package/src/astro-server.ts +2 -2
  110. package/src/capabilities.ts +48 -21
  111. package/src/compiler-hmr.ts +297 -0
  112. package/src/compiler.ts +127 -25
  113. package/src/core.ts +282 -33
  114. package/src/dom-forms.ts +127 -0
  115. package/src/dom.ts +116 -52
  116. package/src/floating.ts +2 -6
  117. package/src/hot.ts +190 -0
  118. package/src/identity.ts +39 -0
  119. package/src/index.ts +2 -0
  120. package/src/jsx-runtime.ts +6 -26
  121. package/src/jsx-types.d.ts +8 -3
  122. package/src/konva.ts +66 -10
  123. package/src/presence.ts +11 -23
  124. package/src/props.ts +55 -0
  125. package/src/renderer.ts +91 -71
  126. package/src/server-renderer.ts +18 -13
  127. package/src/three.ts +23 -24
  128. package/src/use-loadable.ts +2 -2
  129. package/src/vite.ts +44 -4
  130. package/dist/capabilities-DNcnGRv_.d.ts.map +0 -1
  131. package/dist/capabilities-nOIitQ-_.js +0 -65
  132. package/dist/capabilities-nOIitQ-_.js.map +0 -1
  133. package/dist/core-B4rJ0xdc.js +0 -268
  134. package/dist/core-B4rJ0xdc.js.map +0 -1
  135. package/dist/development/capabilities-nOIitQ-_.js +0 -65
  136. package/dist/development/capabilities-nOIitQ-_.js.map +0 -1
  137. package/dist/development/core-BHA7I1nf.js +0 -271
  138. package/dist/development/core-BHA7I1nf.js.map +0 -1
  139. package/dist/development/dom-DQ0M3rLL.js.map +0 -1
  140. package/dist/development/jsx-runtime.js.map +0 -1
  141. package/dist/development/server-renderer-DCLoMdOX.js.map +0 -1
  142. package/dist/development/src-DoQgCX-O.js.map +0 -1
  143. package/dist/development/vite-Bmyb6P5w.js +0 -265
  144. package/dist/development/vite-Bmyb6P5w.js.map +0 -1
  145. package/dist/dom-D8g3roX9.js.map +0 -1
  146. package/dist/jsx-runtime-DQnpyT_g.d.ts.map +0 -1
  147. package/dist/jsx-runtime.js.map +0 -1
  148. package/dist/server-renderer-D0rsFL_-.js.map +0 -1
  149. package/dist/src-Bme1kz2b.js.map +0 -1
  150. package/dist/vite-Bmyb6P5w.js +0 -265
  151. package/dist/vite-Bmyb6P5w.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atom.io/spa",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "description": "An atom.io-driven JSX renderer.",
5
5
  "homepage": "https://atom.io.fyi/docs/spa",
6
6
  "repository": {
@@ -38,6 +38,11 @@
38
38
  "development": "./dist/development/vite.js",
39
39
  "import": "./dist/vite.js"
40
40
  },
41
+ "./hot": {
42
+ "types": "./dist/hot.d.ts",
43
+ "development": "./dist/development/hot.js",
44
+ "import": "./dist/hot.js"
45
+ },
41
46
  "./astro": {
42
47
  "types": "./dist/astro.d.ts",
43
48
  "development": "./dist/development/astro.js",
@@ -107,9 +112,10 @@
107
112
  "src"
108
113
  ],
109
114
  "dependencies": {
115
+ "@jridgewell/remapping": "2.3.5",
110
116
  "html-entities": "2.6.0",
111
117
  "magic-string": "1.4.5",
112
- "oxc-parser": "0.157.0"
118
+ "oxc-parser": "0.158.0"
113
119
  },
114
120
  "devDependencies": {
115
121
  "@breakage/changesets": "0.1.0",
@@ -118,22 +124,22 @@
118
124
  "@types/node": "26.6.6",
119
125
  "@types/three": "0.187.0",
120
126
  "@vitest/coverage-v8": "5.1.0",
121
- "astro": "7.4.7",
122
- "atom.io": "0.54.8",
127
+ "astro": "7.4.8",
128
+ "atom.io": "0.54.9",
123
129
  "breakage": "0.10.2",
124
130
  "esbuild": "0.28.2",
125
131
  "eslint": "10.14.0",
126
132
  "happy-dom": "21.0.4",
127
133
  "konva": "10.9.1",
128
- "motion": "14.10.1",
134
+ "motion": "14.11.1",
129
135
  "playwright": "1.65.0",
130
136
  "preact": "11.2.0",
131
137
  "resumability": "0.0.2",
132
- "rolldown": "1.3.0",
138
+ "rolldown": "1.3.1",
133
139
  "three": "0.187.0",
134
140
  "tsdown": "0.23.7",
135
141
  "typescript": "7.0.2",
136
- "vite": "8.3.6",
142
+ "vite": "8.3.7",
137
143
  "vitest": "5.1.0"
138
144
  },
139
145
  "peerDependencies": {
@@ -188,7 +194,7 @@
188
194
  "test:once": "vitest run --config vitest.config.ts && pnpm test:consumer && pnpm test:optional-peers",
189
195
  "test:consumer": "node __tests__/fixtures/consumer/check.ts",
190
196
  "test:production": "node scripts/production-test.ts",
191
- "test:browser": "astro build --root __tests__/astro && node scripts/browser-test.mjs && node scripts/dev-browser-test.mjs && node scripts/graphics-browser-test.mjs && node scripts/layout-browser-test.mjs && pnpm test:browser:resumption",
197
+ "test:browser": "astro build --root __tests__/astro && node scripts/browser-test.mjs && node scripts/dev-browser-test.mjs && node scripts/graphics-browser-test.mjs && node scripts/layout-browser-test.mjs && pnpm test:browser:hmr && pnpm test:browser:resumption",
192
198
  "test:browser:dev": "node scripts/dev-browser-test.mjs",
193
199
  "cov": "vitest run --config vitest.config.ts --coverage",
194
200
  "readme:write": "galley write README.mdx",
@@ -203,6 +209,7 @@
203
209
  "example:floating": "vite --config examples/floating/vite.config.ts",
204
210
  "test:browser:floating": "node scripts/floating-browser-test.mjs",
205
211
  "test:browser:resumption": "astro build --root __tests__/resumption && node scripts/resumption-browser-test.mjs && node scripts/resumption-browser-test.mjs --dev",
206
- "test:browser:layout": "node scripts/layout-browser-test.mjs"
212
+ "test:browser:layout": "node scripts/layout-browser-test.mjs",
213
+ "test:browser:hmr": "node scripts/hmr-browser-test.mjs && node scripts/hmr-astro-browser-test.mjs"
207
214
  }
208
215
  }
@@ -13,8 +13,9 @@ import { browserApplication } from "./astro-application.ts"
13
13
  import { failPreparation, storeContext } from "./astro-context.ts"
14
14
  import type { AstroStorePreparation, Island } from "./astro-shared.ts"
15
15
  import { island, islandStore } from "./astro-shared.ts"
16
- import { onCleanup, useGetter } from "./core.ts"
16
+ import { useGetter } from "./core.ts"
17
17
  import { hydrate, render } from "./dom.ts"
18
+ import { onRootDispose } from "./hot.ts"
18
19
 
19
20
  type Props = Record<string, any>
20
21
  type Slots = Record<string, string>
@@ -111,7 +112,7 @@ export const createHydrator =
111
112
  disposeFromStore(store!, state)
112
113
  })
113
114
  const mount = () => {
114
- onCleanup(dispose)
115
+ onRootDispose(dispose)
115
116
  const getState = useGetter(state)
116
117
  return () => island(component, getState().props, getState().slots)
117
118
  }
@@ -49,8 +49,8 @@ export const createRenderer = (
49
49
  () => () => island(component, props, slots),
50
50
  options,
51
51
  awaitState
52
- ? (value, token) => {
53
- reads.set(token.key, token)
52
+ ? (value, token, readStore) => {
53
+ if (readStore === store) reads.set(token.key, token)
54
54
  if (value instanceof Promise) {
55
55
  pending.add(value)
56
56
  }
@@ -1,4 +1,5 @@
1
1
  import type { Cleanup, Root, Scope } from "./core.ts"
2
+ import { isPresent, scopeCapabilities } from "./core.ts"
2
3
  import type { ExitHandle, PresenceCoordinator } from "./presence.ts"
3
4
 
4
5
  /** Native renderers expose property access without importing capability engines. */
@@ -26,6 +27,7 @@ export interface Capability {
26
27
  /** SPA supplies ownership for integrations that measure after mount or report async errors. */
27
28
  attach(target: CapabilityTarget, scope?: Scope): CapabilityBinding
28
29
  }
30
+ type EventHandler = (this: unknown, ...args: unknown[]) => unknown
29
31
 
30
32
  export function capabilityNamespace(key: string): string | undefined {
31
33
  const colon = key.indexOf(`:`)
@@ -33,16 +35,25 @@ export function capabilityNamespace(key: string): string | undefined {
33
35
  const namespace = key.slice(0, colon)
34
36
  return /^(xml|xmlns|xlink)$/.test(namespace) ? undefined : namespace
35
37
  }
38
+ function requireCapability(
39
+ capabilities: Map<string, Capability>,
40
+ namespace: string,
41
+ ) {
42
+ const capability = capabilities.get(namespace)
43
+ if (!capability)
44
+ throw new Error(
45
+ `spa: capability "${namespace}" is not registered for this root`,
46
+ )
47
+ return capability
48
+ }
36
49
  export function validateCapabilities(
37
50
  scope: Scope,
38
51
  props: Record<string, unknown>,
39
52
  ): void {
53
+ const capabilities = scopeCapabilities(scope)
40
54
  for (const key of Object.keys(props)) {
41
55
  const namespace = capabilityNamespace(key)
42
- if (namespace && !scope._root._capabilities.has(namespace))
43
- throw new Error(
44
- `spa: capability "${namespace}" is not registered for this root`,
45
- )
56
+ if (namespace) requireCapability(capabilities, namespace)
46
57
  }
47
58
  }
48
59
 
@@ -53,9 +64,24 @@ export function capabilityProps(
53
64
  read?: () => Record<string, any>,
54
65
  applyNative?: (props: Record<string, any>) => string | undefined,
55
66
  ): (props: Record<string, any>) => Record<string, any> {
56
- const bindings = new Map<string, CapabilityBinding>()
67
+ const root = scope._root
68
+ const bindings = new Map<Capability, CapabilityBinding>()
69
+ let handlers: WeakMap<EventHandler, EventHandler> | undefined
70
+ const event = (handler: EventHandler) => {
71
+ const cache = (handlers ??= new WeakMap())
72
+ let wrapped = cache.get(handler)
73
+ if (!wrapped) {
74
+ wrapped = function (this: unknown, ...args: unknown[]) {
75
+ // Presence may activate after this listener mounts.
76
+ if (!root._presence || isPresent(scope)) return handler.apply(this, args)
77
+ }
78
+ cache.set(handler, wrapped)
79
+ }
80
+ return wrapped
81
+ }
57
82
 
58
- scope._root._presence?.target(scope, target)
83
+ if (root._presence) root._presence.target(scope, target)
84
+ else (scope._targets ??= new Set()).add(target)
59
85
  const cleanup: Cleanup = () => {
60
86
  const errors: unknown[] = []
61
87
  for (const binding of [...bindings.values()].reverse()) {
@@ -70,43 +96,44 @@ export function capabilityProps(
70
96
  }
71
97
  scope._cleanups.add(cleanup)
72
98
  return (props) => {
73
- validateCapabilities(scope, props)
99
+ const capabilities = scopeCapabilities(scope)
74
100
  const native: Record<string, any> = {}
75
- const groups = new Map<string, Record<string, unknown>>()
101
+ const groups = new Map<Capability, Record<string, unknown>>()
76
102
  for (const key of Object.keys(props)) {
77
103
  const namespace = capabilityNamespace(key)
78
104
  if (!namespace) {
79
105
  const value = props[key]
80
106
  native[key] =
81
107
  key.startsWith(`on`) && typeof value === `function`
82
- ? (scope._root._presence?.event(scope, value) ?? value)
108
+ ? event(value)
83
109
  : value
84
110
  continue
85
111
  }
86
- const group = groups.get(namespace) ?? {}
112
+ const capability = requireCapability(capabilities, namespace)
113
+ const group = groups.get(capability) ?? {}
87
114
  group[key.slice(namespace.length + 1)] = props[key]
88
- groups.set(namespace, group)
115
+ groups.set(capability, group)
89
116
  }
90
117
  const previousStyle = applyNative?.(native)
91
- for (const [namespace, values] of groups) {
92
- let binding = bindings.get(namespace)
118
+ for (const [capability, values] of groups) {
119
+ let binding = bindings.get(capability)
93
120
  if (!binding) {
94
- binding = scope._root._capabilities.get(namespace)!.attach(target, scope)
95
- bindings.set(namespace, binding)
96
- scope._root._presence?.bind(
121
+ binding = capability.attach(target, scope)
122
+ bindings.set(capability, binding)
123
+ root._presence?.bind(
97
124
  scope,
98
125
  binding,
99
126
  read ?? (() => props),
100
- namespace,
127
+ capability.namespace,
101
128
  )
102
129
  }
103
130
  if (previousStyle !== undefined) binding.update(values, previousStyle)
104
131
  else binding.update(values)
105
132
  }
106
- for (const [namespace, binding] of bindings)
107
- if (!groups.has(namespace)) {
108
- bindings.delete(namespace)
109
- scope._root._presence?.unbind(binding)
133
+ for (const [capability, binding] of bindings)
134
+ if (!groups.has(capability)) {
135
+ bindings.delete(capability)
136
+ root._presence?.unbind(binding)
110
137
  binding.dispose()
111
138
  }
112
139
  return native
@@ -0,0 +1,297 @@
1
+ import remapping from "@jridgewell/remapping"
2
+ import type { SourceMap } from "magic-string"
3
+ import MagicString from "magic-string"
4
+ import type { Node } from "oxc-parser"
5
+ import { parseSync, visitorKeys } from "oxc-parser"
6
+
7
+ function walk(node: Node, visit: (node: Node) => void): void {
8
+ visit(node)
9
+ for (const key of visitorKeys[node.type]) {
10
+ const value = (node as unknown as Record<string, unknown>)[key]
11
+ if (Array.isArray(value)) {
12
+ for (const child of value) if (child) walk(child, visit)
13
+ } else if (value) walk(value as Node, visit)
14
+ }
15
+ }
16
+ const factories = new Set([
17
+ `atom`,
18
+ `atomFamily`,
19
+ `selector`,
20
+ `selectorFamily`,
21
+ `transaction`,
22
+ `timeline`,
23
+ `timelineFamily`,
24
+ `Silo`,
25
+ ])
26
+ function stateIn(program: Node): boolean {
27
+ const names = new Set(factories)
28
+ walk(program, (node) => {
29
+ if (
30
+ node.type === `ImportDeclaration` &&
31
+ node.source.value.startsWith(`atom.io`)
32
+ ) {
33
+ for (const specifier of node.specifiers) {
34
+ if (
35
+ specifier.type === `ImportSpecifier` &&
36
+ specifier.imported.type === `Identifier` &&
37
+ factories.has(specifier.imported.name)
38
+ )
39
+ names.add(specifier.local.name)
40
+ }
41
+ }
42
+ })
43
+ let found = false
44
+ walk(program, (node) => {
45
+ if (node.type === `CallExpression` || node.type === `NewExpression`) {
46
+ const callee = node.callee
47
+ if (
48
+ (callee.type === `Identifier` && names.has(callee.name)) ||
49
+ (callee.type === `MemberExpression` &&
50
+ !callee.computed &&
51
+ callee.property.type === `Identifier` &&
52
+ factories.has(callee.property.name))
53
+ )
54
+ found = true
55
+ }
56
+ })
57
+ return found
58
+ }
59
+
60
+ export function requiresModuleReload(code: string, filename: string): boolean {
61
+ const program = parseSync(filename, code, { lang: `tsx` }).program
62
+ return (
63
+ stateIn(program) ||
64
+ program.body.some((node) => {
65
+ if (node.type === `ExportDefaultDeclaration`) return true
66
+ if (node.type === `ExportAllDeclaration`) return node.exportKind !== `type`
67
+ if (node.type !== `ExportNamedDeclaration` || node.exportKind === `type`)
68
+ return false
69
+ if (node.declaration)
70
+ return ![
71
+ `TSInterfaceDeclaration`,
72
+ `TSTypeAliasDeclaration`,
73
+ `TSDeclareFunction`,
74
+ ].includes(node.declaration.type)
75
+ return node.specifiers.some((specifier) => specifier.exportKind !== `type`)
76
+ })
77
+ )
78
+ }
79
+
80
+ /** Instrument only local component exports, composing both edits back to authored JSX. */
81
+ export function hotModule(
82
+ code: string,
83
+ filename: string,
84
+ originalMap: SourceMap,
85
+ ):
86
+ | {
87
+ code: string
88
+ map: string
89
+ exports: string[]
90
+ }
91
+ | undefined {
92
+ const program = parseSync(filename, code, {
93
+ lang: `tsx`,
94
+ preserveParens: true,
95
+ }).program
96
+ if (stateIn(program)) return
97
+ const components = new Set<string>()
98
+ const declarations = new Map<string, Node>()
99
+ const exports = new Map<string, string[]>()
100
+ const defaults: Extract<Node, { type: `ExportDefaultDeclaration` }>[] = []
101
+ const identifiers = new Set<string>()
102
+ walk(program, (node) => {
103
+ if (node.type === `Identifier`) identifiers.add(node.name)
104
+ })
105
+ const branded = (node: Node): boolean => {
106
+ if (
107
+ node.type !== `ExpressionStatement` ||
108
+ node.expression.type !== `AssignmentExpression`
109
+ )
110
+ return false
111
+ const { left, right } = node.expression
112
+ if (
113
+ left.type !== `MemberExpression` ||
114
+ left.computed ||
115
+ left.object.type !== `Identifier` ||
116
+ left.property.type !== `Identifier` ||
117
+ left.property.name !== `spa` ||
118
+ right.type !== `Literal` ||
119
+ right.value !== true
120
+ )
121
+ return false
122
+ components.add(left.object.name)
123
+ return true
124
+ }
125
+ const declaration = (node: Node): boolean => {
126
+ if (node.type === `FunctionDeclaration` && node.id) {
127
+ declarations.set(node.id.name, node)
128
+ return true
129
+ }
130
+ if (node.type === `VariableDeclaration`) {
131
+ for (const entry of node.declarations) {
132
+ if (entry.id.type === `Identifier`) declarations.set(entry.id.name, node)
133
+ let unsafe = false
134
+ let init = entry.init
135
+ while (init?.type === `ParenthesizedExpression`) init = init.expression
136
+ if (
137
+ init &&
138
+ init.type !== `ArrowFunctionExpression` &&
139
+ init.type !== `FunctionExpression`
140
+ )
141
+ walk(init, (child) => {
142
+ if (
143
+ [
144
+ `CallExpression`,
145
+ `NewExpression`,
146
+ `TaggedTemplateExpression`,
147
+ ].includes(child.type)
148
+ )
149
+ unsafe = true
150
+ })
151
+ if (unsafe) return false
152
+ }
153
+ return true
154
+ }
155
+ return [
156
+ `TSInterfaceDeclaration`,
157
+ `TSTypeAliasDeclaration`,
158
+ `TSDeclareFunction`,
159
+ ].includes(node.type)
160
+ }
161
+ const add = (local: string, exported: string) => {
162
+ exports.set(local, [...(exports.get(local) ?? []), exported])
163
+ }
164
+ for (const statement of program.body) {
165
+ if (
166
+ statement.type === `ExportAllDeclaration` &&
167
+ statement.exportKind === `type`
168
+ )
169
+ continue
170
+ if (
171
+ statement.type === `ImportDeclaration` ||
172
+ statement.type === `EmptyStatement`
173
+ )
174
+ continue
175
+ if (
176
+ statement.type === `ExpressionStatement` &&
177
+ (statement.directive || branded(statement))
178
+ )
179
+ continue
180
+ if (statement.type === `ExportNamedDeclaration`) {
181
+ if (statement.exportKind === `type`) continue
182
+ if (statement.source) return
183
+ if (statement.declaration) {
184
+ const node = statement.declaration
185
+ if (!declaration(node)) return
186
+ if (node.type === `FunctionDeclaration` && node.id)
187
+ add(node.id.name, node.id.name)
188
+ if (node.type === `VariableDeclaration`)
189
+ for (const entry of node.declarations) {
190
+ if (entry.id.type !== `Identifier`) return
191
+ add(entry.id.name, entry.id.name)
192
+ }
193
+ } else
194
+ for (const specifier of statement.specifiers) {
195
+ if (specifier.exportKind === `type`) continue
196
+ add(
197
+ // Local export names are identifiers; string names require a source above.
198
+ (specifier.local as { name: string }).name,
199
+ specifier.exported.type === `Identifier`
200
+ ? specifier.exported.name
201
+ : specifier.exported.value,
202
+ )
203
+ }
204
+ } else if (statement.type === `ExportDefaultDeclaration`) {
205
+ const node = statement.declaration
206
+ if (node.type === `Identifier`) add(node.name, `default`)
207
+ else if (node.type === `FunctionDeclaration` && node.id) {
208
+ declaration(node)
209
+ add(node.id.name, `default`)
210
+ } else return
211
+ defaults.push(statement)
212
+ } else if (!declaration(statement)) return
213
+ }
214
+ if (
215
+ !exports.size ||
216
+ [...exports.keys()].some(
217
+ (name) => !components.has(name) || !declarations.has(name),
218
+ )
219
+ )
220
+ return
221
+ const output = new MagicString(code)
222
+ const mutable = new Set<Node>()
223
+ for (const name of exports.keys()) {
224
+ const node = declarations.get(name)!
225
+ if (
226
+ node.type === `VariableDeclaration` &&
227
+ node.kind === `const` &&
228
+ !mutable.has(node)
229
+ ) {
230
+ output.update(node.start, node.start + 5, `let`)
231
+ mutable.add(node)
232
+ }
233
+ }
234
+ for (const node of defaults) {
235
+ const value = node.declaration
236
+ const name =
237
+ value.type === `Identifier`
238
+ ? value.name
239
+ : (value as { id: { name: string } }).id.name
240
+ const prefix = code.slice(node.start, value.start)
241
+ for (const token of prefix.matchAll(
242
+ /\/\*[\s\S]*?\*\/|\/\/[^\r\n]*|\b(?:export|default)\b/g,
243
+ )) {
244
+ if (token[0] === `export` || token[0] === `default`)
245
+ output.update(
246
+ node.start + token.index,
247
+ node.start + token.index + token[0].length,
248
+ value.type === `Identifier` && token[0] === `export` ? `export {` : ``,
249
+ )
250
+ }
251
+ if (value.type === `Identifier`)
252
+ output.appendLeft(value.end, ` as default }`)
253
+ else output.appendLeft(node.end, `;\nexport { ${name} as default };`)
254
+ }
255
+ const uid = (base: string) => {
256
+ let name = base
257
+ while (identifiers.has(name)) name += `_`
258
+ identifiers.add(name)
259
+ return name
260
+ }
261
+ const register = uid(`__spaHotRegister`),
262
+ refresh = uid(`__spaHotRefresh`)
263
+ let position = program.hashbang?.end ?? 0
264
+ for (const statement of program.body) {
265
+ if (statement.type !== `ExpressionStatement` || !statement.directive) break
266
+ position = statement.end
267
+ }
268
+ output.appendLeft(
269
+ position,
270
+ `\nimport { registerComponent as ${register}, refresh as ${refresh} } from "@atom.io/spa/hot";\n`,
271
+ )
272
+ output.append(`\nif (import.meta.hot) {\n`)
273
+ for (const [name, aliases] of exports)
274
+ output.append(
275
+ `${name} = ${register}(${JSON.stringify(filename)}, ${JSON.stringify(aliases.sort()[0])}, ${name});\n`,
276
+ )
277
+ output.append(
278
+ `import.meta.hot.accept(() => ${refresh}(${JSON.stringify(filename)}));\n}\n`,
279
+ )
280
+ return {
281
+ code: output.toString(),
282
+ map: remapping(
283
+ [
284
+ output
285
+ .generateMap({
286
+ source: filename,
287
+ includeContent: true,
288
+ hires: true,
289
+ })
290
+ .toString(),
291
+ originalMap.toString(),
292
+ ],
293
+ () => null,
294
+ ).toString(),
295
+ exports: [...exports.values()].flat().sort(),
296
+ }
297
+ }