@proveanything/smartlinks 3.0.0-alpha.1 → 3.0.0-alpha.3

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 (272) hide show
  1. package/README.md +741 -741
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/analytics.d.ts +5 -4
  5. package/dist/api/analytics.js +5 -4
  6. package/dist/api/appConfiguration.d.ts +23 -18
  7. package/dist/api/appConfiguration.js +24 -18
  8. package/dist/api/appObjects.d.ts +54 -10
  9. package/dist/api/appObjects.js +75 -40
  10. package/dist/api/asset.d.ts +28 -22
  11. package/dist/api/asset.js +45 -56
  12. package/dist/api/attestation.d.ts +11 -3
  13. package/dist/api/attestation.js +12 -3
  14. package/dist/api/attestations.d.ts +12 -8
  15. package/dist/api/attestations.js +18 -21
  16. package/dist/api/authKit.d.ts +15 -10
  17. package/dist/api/authKit.js +17 -11
  18. package/dist/api/batch.d.ts +36 -25
  19. package/dist/api/batch.js +46 -39
  20. package/dist/api/bookings.d.ts +67 -11
  21. package/dist/api/bookings.js +82 -15
  22. package/dist/api/broadcasts.js +3 -17
  23. package/dist/api/claimSet.d.ts +26 -12
  24. package/dist/api/claimSet.js +32 -24
  25. package/dist/api/collection.d.ts +15 -10
  26. package/dist/api/collection.js +17 -11
  27. package/dist/api/comms.d.ts +12 -6
  28. package/dist/api/comms.js +12 -6
  29. package/dist/api/conditions.d.ts +7 -6
  30. package/dist/api/conditions.js +8 -6
  31. package/dist/api/contact.d.ts +6 -2
  32. package/dist/api/contact.js +25 -60
  33. package/dist/api/containers.d.ts +14 -10
  34. package/dist/api/containers.js +19 -14
  35. package/dist/api/crate.js +7 -9
  36. package/dist/api/dpp.d.ts +20 -13
  37. package/dist/api/dpp.js +23 -15
  38. package/dist/api/facets.d.ts +38 -13
  39. package/dist/api/facets.js +40 -15
  40. package/dist/api/files.d.ts +5 -2
  41. package/dist/api/files.js +7 -4
  42. package/dist/api/form.d.ts +8 -5
  43. package/dist/api/form.js +9 -5
  44. package/dist/api/index.d.ts +1 -1
  45. package/dist/api/index.js +1 -1
  46. package/dist/api/integrations.d.ts +29 -17
  47. package/dist/api/integrations.js +32 -25
  48. package/dist/api/interactions.d.ts +11 -6
  49. package/dist/api/interactions.js +14 -23
  50. package/dist/api/jobs.d.ts +16 -6
  51. package/dist/api/jobs.js +30 -20
  52. package/dist/api/journeys.js +2 -14
  53. package/dist/api/journeysAnalytics.d.ts +8 -5
  54. package/dist/api/journeysAnalytics.js +8 -5
  55. package/dist/api/knowledge.d.ts +20 -14
  56. package/dist/api/knowledge.js +22 -15
  57. package/dist/api/location.d.ts +6 -3
  58. package/dist/api/location.js +8 -22
  59. package/dist/api/lots.d.ts +9 -5
  60. package/dist/api/lots.js +22 -26
  61. package/dist/api/loyalty.d.ts +25 -16
  62. package/dist/api/loyalty.js +33 -32
  63. package/dist/api/nfc.d.ts +3 -1
  64. package/dist/api/nfc.js +3 -1
  65. package/dist/api/order.d.ts +45 -39
  66. package/dist/api/order.js +48 -65
  67. package/dist/api/partner.d.ts +17 -14
  68. package/dist/api/partner.js +21 -22
  69. package/dist/api/payments.d.ts +60 -0
  70. package/dist/api/payments.js +94 -0
  71. package/dist/api/products.d.ts +35 -12
  72. package/dist/api/products.js +36 -13
  73. package/dist/api/proof.d.ts +41 -19
  74. package/dist/api/proof.js +44 -23
  75. package/dist/api/realtime.d.ts +3 -0
  76. package/dist/api/realtime.js +10 -2
  77. package/dist/api/segments.js +3 -15
  78. package/dist/api/serviceAccounts.d.ts +8 -5
  79. package/dist/api/serviceAccounts.js +9 -6
  80. package/dist/api/shop.d.ts +7 -5
  81. package/dist/api/shop.js +13 -19
  82. package/dist/api/subscriptions.d.ts +12 -10
  83. package/dist/api/subscriptions.js +17 -25
  84. package/dist/api/tags.d.ts +23 -20
  85. package/dist/api/tags.js +40 -52
  86. package/dist/api/template.d.ts +16 -11
  87. package/dist/api/template.js +19 -13
  88. package/dist/api/translations.js +2 -12
  89. package/dist/api/userGroups.d.ts +26 -16
  90. package/dist/api/userGroups.js +43 -30
  91. package/dist/api/variant.d.ts +10 -7
  92. package/dist/api/variant.js +11 -7
  93. package/dist/api/wallet.d.ts +14 -11
  94. package/dist/api/wallet.js +15 -12
  95. package/dist/baseline.css +194 -194
  96. package/dist/dataChanged.d.ts +74 -0
  97. package/dist/dataChanged.js +162 -0
  98. package/dist/docs/API_SUMMARY.md +1443 -1409
  99. package/dist/docs/admin-cards.md +189 -189
  100. package/dist/docs/agent-tools.md +156 -156
  101. package/dist/docs/ai-tools-and-skills.md +180 -180
  102. package/dist/docs/ai.md +1721 -1721
  103. package/dist/docs/analytics.md +1 -1
  104. package/dist/docs/api-versions.md +85 -85
  105. package/dist/docs/app-data-storage.md +277 -277
  106. package/dist/docs/app-docs.md +73 -73
  107. package/dist/docs/app-manifest.md +852 -852
  108. package/dist/docs/app-objects.md +4 -4
  109. package/dist/docs/app-records-pattern.md +388 -388
  110. package/dist/docs/appConfig.md +550 -550
  111. package/dist/docs/assistant-apps.md +172 -172
  112. package/dist/docs/assistant-context.md +119 -119
  113. package/dist/docs/attestations.md +8 -8
  114. package/dist/docs/bookings.md +105 -8
  115. package/dist/docs/caching.md +32 -3
  116. package/dist/docs/comms.md +689 -689
  117. package/dist/docs/connectors.md +340 -340
  118. package/dist/docs/contact-search.md +2 -3
  119. package/dist/docs/css-baseline.md +133 -133
  120. package/dist/docs/customer-guide.md +70 -70
  121. package/dist/docs/data-changed.md +91 -0
  122. package/dist/docs/deploying-apps.md +340 -340
  123. package/dist/docs/dpp.md +115 -115
  124. package/dist/docs/entitlements.md +90 -90
  125. package/dist/docs/files.md +69 -69
  126. package/dist/docs/host-dependency-contract.md +252 -252
  127. package/dist/docs/iframe-responder.md +11 -0
  128. package/dist/docs/integrations.md +322 -322
  129. package/dist/docs/interactions.md +544 -544
  130. package/dist/docs/item-context.md +181 -181
  131. package/dist/docs/knowledge.md +105 -105
  132. package/dist/docs/lists.md +157 -114
  133. package/dist/docs/lots.md +112 -112
  134. package/dist/docs/loyalty.md +348 -348
  135. package/dist/docs/members.md +183 -183
  136. package/dist/docs/memberships.md +150 -150
  137. package/dist/docs/mobile-admin-container.md +693 -693
  138. package/dist/docs/operations.md +281 -281
  139. package/dist/docs/overview.md +487 -485
  140. package/dist/docs/payments.md +94 -0
  141. package/dist/docs/proof-comms-triggers.md +142 -142
  142. package/dist/docs/proof-ownership-transfer.md +155 -155
  143. package/dist/docs/proof-product-data-scoping.md +462 -462
  144. package/dist/docs/proof-share-grants.md +305 -305
  145. package/dist/docs/realtime.md +149 -139
  146. package/dist/docs/records-admin-pattern.md +304 -304
  147. package/dist/docs/service-accounts.md +64 -64
  148. package/dist/docs/standard-query.md +196 -187
  149. package/dist/docs/tag-codes.md +97 -97
  150. package/dist/docs/tag-ranges.md +106 -106
  151. package/dist/docs/theme-tokens.md +252 -252
  152. package/dist/docs/upgrading-to-3.md +550 -430
  153. package/dist/docs/wallet-passes.md +107 -107
  154. package/dist/docs/websites.md +123 -123
  155. package/dist/http.d.ts +6 -3
  156. package/dist/http.js +48 -19
  157. package/dist/iframeResponder.d.ts +7 -0
  158. package/dist/iframeResponder.js +10 -0
  159. package/dist/index.d.ts +2 -0
  160. package/dist/index.js +2 -0
  161. package/dist/list.d.ts +12 -0
  162. package/dist/list.js +59 -0
  163. package/dist/openapi.yaml +722 -660
  164. package/dist/testing/bookingsMemory.d.ts +29 -1
  165. package/dist/testing/bookingsMemory.js +89 -1
  166. package/dist/testing/index.js +4 -1
  167. package/dist/theme-boot.js +82 -82
  168. package/dist/theme.css +75 -75
  169. package/dist/types/analytics.d.ts +7 -3
  170. package/dist/types/appManifest.d.ts +26 -4
  171. package/dist/types/appObjects.d.ts +27 -12
  172. package/dist/types/appOptions.d.ts +2 -2
  173. package/dist/types/asset.d.ts +5 -6
  174. package/dist/types/attestations.d.ts +7 -9
  175. package/dist/types/batch.d.ts +5 -5
  176. package/dist/types/bookings.d.ts +109 -6
  177. package/dist/types/comms.d.ts +9 -5
  178. package/dist/types/contact.d.ts +7 -4
  179. package/dist/types/containers.d.ts +2 -1
  180. package/dist/types/facets.d.ts +14 -2
  181. package/dist/types/files.d.ts +3 -2
  182. package/dist/types/index.d.ts +1 -0
  183. package/dist/types/index.js +1 -0
  184. package/dist/types/integrations.d.ts +2 -1
  185. package/dist/types/interaction.d.ts +15 -7
  186. package/dist/types/jobs.d.ts +1 -1
  187. package/dist/types/journeysAnalytics.d.ts +3 -2
  188. package/dist/types/knowledge.d.ts +6 -3
  189. package/dist/types/knowledge.js +0 -1
  190. package/dist/types/list.d.ts +30 -2
  191. package/dist/types/location.d.ts +7 -2
  192. package/dist/types/location.js +0 -1
  193. package/dist/types/lots.d.ts +5 -2
  194. package/dist/types/lots.js +0 -6
  195. package/dist/types/order.d.ts +22 -20
  196. package/dist/types/payments.d.ts +101 -0
  197. package/dist/types/payments.js +5 -0
  198. package/dist/types/product.d.ts +28 -11
  199. package/dist/types/proof.d.ts +7 -8
  200. package/dist/types/realtime.d.ts +5 -1
  201. package/dist/types/tags.d.ts +5 -3
  202. package/dist/types/userGroups.d.ts +3 -3
  203. package/dist/types/userGroups.js +0 -4
  204. package/dist/version.d.ts +1 -1
  205. package/dist/version.js +1 -1
  206. package/docs/API_SUMMARY.md +1443 -1409
  207. package/docs/admin-cards.md +189 -189
  208. package/docs/agent-tools.md +156 -156
  209. package/docs/ai-tools-and-skills.md +180 -180
  210. package/docs/ai.md +1721 -1721
  211. package/docs/analytics.md +1 -1
  212. package/docs/api-versions.md +85 -85
  213. package/docs/app-data-storage.md +277 -277
  214. package/docs/app-docs.md +73 -73
  215. package/docs/app-manifest.md +852 -852
  216. package/docs/app-objects.md +4 -4
  217. package/docs/app-records-pattern.md +388 -388
  218. package/docs/appConfig.md +550 -550
  219. package/docs/assistant-apps.md +172 -172
  220. package/docs/assistant-context.md +119 -119
  221. package/docs/attestations.md +8 -8
  222. package/docs/bookings.md +105 -8
  223. package/docs/caching.md +32 -3
  224. package/docs/comms.md +689 -689
  225. package/docs/connectors.md +340 -340
  226. package/docs/contact-search.md +2 -3
  227. package/docs/css-baseline.md +133 -133
  228. package/docs/customer-guide.md +70 -70
  229. package/docs/data-changed.md +91 -0
  230. package/docs/deploying-apps.md +340 -340
  231. package/docs/dpp.md +115 -115
  232. package/docs/entitlements.md +90 -90
  233. package/docs/files.md +69 -69
  234. package/docs/host-dependency-contract.md +252 -252
  235. package/docs/iframe-responder.md +11 -0
  236. package/docs/integrations.md +322 -322
  237. package/docs/interactions.md +544 -544
  238. package/docs/item-context.md +181 -181
  239. package/docs/knowledge.md +105 -105
  240. package/docs/lists.md +157 -114
  241. package/docs/lots.md +112 -112
  242. package/docs/loyalty.md +348 -348
  243. package/docs/members.md +183 -183
  244. package/docs/memberships.md +150 -150
  245. package/docs/mobile-admin-container.md +693 -693
  246. package/docs/operations.md +281 -281
  247. package/docs/overview.md +487 -485
  248. package/docs/payments.md +94 -0
  249. package/docs/proof-comms-triggers.md +142 -142
  250. package/docs/proof-ownership-transfer.md +155 -155
  251. package/docs/proof-product-data-scoping.md +462 -462
  252. package/docs/proof-share-grants.md +305 -305
  253. package/docs/realtime.md +149 -139
  254. package/docs/service-accounts.md +64 -64
  255. package/docs/standard-query.md +196 -187
  256. package/docs/tag-codes.md +97 -97
  257. package/docs/tag-ranges.md +106 -106
  258. package/docs/theme-lookbook.v1.json +120 -120
  259. package/docs/theme-tokens.md +252 -252
  260. package/docs/upgrading-to-3.md +550 -430
  261. package/docs/wallet-passes.md +107 -107
  262. package/docs/websites.md +123 -123
  263. package/openapi.yaml +722 -660
  264. package/package.json +91 -91
  265. package/scripts/headless-check.mjs +87 -87
  266. package/scripts/lib/bare-imports.mjs +57 -57
  267. package/scripts/lib/keyed-app-data.mjs +21 -21
  268. package/scripts/lib/upgrade.mjs +708 -512
  269. package/scripts/publish.mjs +272 -272
  270. package/scripts/register-release.mjs +91 -91
  271. package/scripts/upgrade.mjs +79 -56
  272. package/upgrade/3.json +2731 -2213
@@ -1,512 +1,708 @@
1
- // =============================================================================
2
- // Moving an app to a new major of the SDK: what a script can safely do, and a list of everything else.
3
- //
4
- // Reads upgrade/<major>.json (the same table docs/upgrading-to-<major>.md is filled from) and the app's
5
- // source, and:
6
- // 1. plans the MECHANICAL edits: a call that only changed name, an argument that went, the manifest's
7
- // shared-dependency contract. Nothing that changes what the code means.
8
- // 2. lists every other place the table says needs a person or an agent: each call to a list whose
9
- // shape changed, each removed call, each option that went, each thing to check at run time.
10
- //
11
- // It finds SDK calls by what a name is BOUND to, not by its spelling: `product.get(…)` is only an SDK
12
- // call where `product` is the SDK's export (an import, `SL.product`, or taken from one of those). A
13
- // local variable that happens to be called `product` is never touched.
14
- //
15
- // Used by scripts/upgrade.mjs (the `smartlinks-upgrade` command) and by the SDK's tests.
16
- // =============================================================================
17
-
18
- import fs from 'node:fs'
19
- import path from 'node:path'
20
- import { createRequire } from 'node:module'
21
- import { fileURLToPath } from 'node:url'
22
-
23
- const here = path.dirname(fileURLToPath(import.meta.url))
24
- const SDK = /^@proveanything\/smartlinks(\/.*)?$/
25
- const SOURCE = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/
26
- const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', '.git', '.next', '.output', '.vite', '.turbo', 'coverage', '.forge', '.lovable'])
27
-
28
- /** The upgrade table for a major, from this package. */
29
- export function loadTable(major = '3') {
30
- return JSON.parse(fs.readFileSync(path.join(here, '..', '..', 'upgrade', `${major}.json`), 'utf8'))
31
- }
32
-
33
- /** TypeScript's parser: the app's own copy if it has one, else whatever this package can reach. */
34
- export function loadTypeScript(appDir) {
35
- for (const from of [path.join(appDir, 'package.json'), path.join(here, 'package.json')]) {
36
- try { return createRequire(from)('typescript') } catch { /* try the next place */ }
37
- }
38
- return null
39
- }
40
-
41
- function sourceFiles(appDir) {
42
- const out = []
43
- const walk = (dir, depth) => {
44
- let entries = []
45
- try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
46
- for (const e of entries) {
47
- const p = path.join(dir, e.name)
48
- if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.') && depth < 12) walk(p, depth + 1) }
49
- else if (SOURCE.test(e.name) && !e.name.endsWith('.d.ts')) out.push(p)
50
- }
51
- }
52
- walk(appDir, 0)
53
- return out
54
- }
55
-
56
- // ── the table, indexed ───────────────────────────────────────────────────────────────────────────
57
-
58
- function indexTable(table) {
59
- const renames = new Map() // old full name → new full name, mechanical only
60
- const removed = new Map() // name → entry (also renames a script must not do)
61
- const lists = new Map()
62
- const options = new Map() // name → [entries]
63
- const fields = [] // entries about a field of a type: only a person or a type-check finds these
64
- for (const c of table.changes) {
65
- if (c.kind === 'renamed' && c.mechanical) renames.set(c.name, c.to)
66
- else if (c.kind === 'renamed' || c.kind === 'removed') {
67
- if (c.what === 'field') fields.push(c)
68
- else removed.set(c.name, c)
69
- } else if (c.kind === 'list') lists.set(c.name, c)
70
- else if (c.kind === 'option') options.set(c.name, [...(options.get(c.name) || []), c])
71
- }
72
- const hold = new Map()
73
- for (const h of table.hold || []) for (const n of h.names || []) hold.set(n, h)
74
- return { renames, removed, lists, options, fields, hold, behaviour: table.changes.filter((c) => c.kind === 'behaviour') }
75
- }
76
-
77
- // ── one file ─────────────────────────────────────────────────────────────────────────────────────
78
-
79
- function analyseFile(ts, checker, sf, idx, rel) {
80
- const text = sf.text
81
- const edits = [] // { start, end, text }
82
- const work = [] // { kind, name, line, note, ... }
83
- const lineOf = (node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1
84
- const push = (kind, node, name, extra = {}) => work.push({ kind, file: rel, line: lineOf(node), name, ...extra })
85
-
86
- // 1. What the SDK's names are bound to in this file.
87
- const imports = new Map() // symbol → { imported, local, spec, decl }
88
- const namespaces = new Set() // symbols of `import * as X` / default imports of the SDK
89
- for (const st of sf.statements) {
90
- if (ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier) && SDK.test(st.moduleSpecifier.text) && st.importClause) {
91
- const clause = st.importClause
92
- if (clause.name) { const s = checker.getSymbolAtLocation(clause.name); if (s) namespaces.add(s) }
93
- const nb = clause.namedBindings
94
- if (nb && ts.isNamespaceImport(nb)) { const s = checker.getSymbolAtLocation(nb.name); if (s) namespaces.add(s) }
95
- if (nb && ts.isNamedImports(nb)) {
96
- for (const spec of nb.elements) {
97
- const s = checker.getSymbolAtLocation(spec.name)
98
- if (s) imports.set(s, { imported: (spec.propertyName || spec.name).text, local: spec.name.text, spec, decl: st })
99
- }
100
- }
101
- }
102
- // export { product } from '@proveanything/smartlinks'
103
- if (ts.isExportDeclaration(st) && st.moduleSpecifier && ts.isStringLiteral(st.moduleSpecifier) && SDK.test(st.moduleSpecifier.text) && st.exportClause && ts.isNamedExports(st.exportClause)) {
104
- for (const spec of st.exportClause.elements) {
105
- const name = (spec.propertyName || spec.name).text
106
- const hit = [...idx.renames.keys(), ...idx.removed.keys()].find((n) => n === name || n.startsWith(name + '.'))
107
- if (hit) push('by-hand', spec, name, { note: `Re-exported from the SDK here. \`${name}\` is ${idx.renames.has(hit) ? 'renamed' : 'gone'} in SDK 3: change the re-export, then whatever imports it from this file.` })
108
- }
109
- }
110
- }
111
-
112
- const symbolOf = (id) => {
113
- if (id.parent && ts.isShorthandPropertyAssignment(id.parent) && id.parent.name === id) return checker.getShorthandAssignmentValueSymbol(id.parent)
114
- return checker.getSymbolAtLocation(id)
115
- }
116
-
117
- /** The SDK name an expression stands for (['products', 'list']), [] for the SDK itself, null for anything else. */
118
- const sdkPath = (node, depth = 0) => {
119
- if (!node || depth > 8) return null
120
- if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node) || ts.isAsExpression(node)) return sdkPath(node.expression, depth + 1)
121
- if (ts.isIdentifier(node)) {
122
- const sym = symbolOf(node)
123
- if (sym && imports.has(sym)) return [imports.get(sym).imported]
124
- if (sym && namespaces.has(sym)) return []
125
- // const { product } = SL · const records = SL.app.records
126
- const decl = sym && sym.declarations && sym.declarations[0]
127
- if (decl && ts.isBindingElement(decl) && ts.isObjectBindingPattern(decl.parent) && ts.isVariableDeclaration(decl.parent.parent) && decl.parent.parent.initializer) {
128
- const base = sdkPath(decl.parent.parent.initializer, depth + 1)
129
- const key = decl.propertyName || decl.name
130
- if (base && ts.isIdentifier(key)) return [...base, key.text]
131
- }
132
- if (decl && ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name) && decl.initializer && decl.initializer !== node
133
- && ts.isVariableDeclarationList(decl.parent) && (decl.parent.flags & ts.NodeFlags.Const)) {
134
- const base = sdkPath(decl.initializer, depth + 1)
135
- if (base) return base
136
- }
137
- // The SDK handed over by a host is called SL by convention (window.SL, host.SL, a prop named SL).
138
- if (node.text === 'SL' || node.text === 'SL3') return []
139
- return null
140
- }
141
- if (ts.isPropertyAccessExpression(node)) {
142
- if (node.name.text === 'SL' || node.name.text === 'SL3') return []
143
- const base = sdkPath(node.expression, depth + 1)
144
- return base ? [...base, node.name.text] : null
145
- }
146
- return null
147
- }
148
-
149
- // 2. Every use of an SDK name.
150
- const refs = new Map() // import symbol → [identifier]
151
- const renameRefs = new Map() // import symbol → [{ id, to }]: uses a script may rename
152
- const seen = new Set() // "name@pos": one entry per place
153
-
154
- const objectKeys = (call) => {
155
- const keys = new Set()
156
- for (const a of call.arguments || []) if (ts.isObjectLiteralExpression(a)) for (const p of a.properties) if (p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name))) keys.add(p.name.text)
157
- return keys
158
- }
159
-
160
- const visit = (node) => {
161
- if (ts.isIdentifier(node)) {
162
- const sym = symbolOf(node)
163
- const imp = sym && imports.get(sym)
164
- if (imp && node !== imp.spec.name && node !== imp.spec.propertyName) refs.set(sym, [...(refs.get(sym) || []), node])
165
- }
166
-
167
- const isChainTop = (ts.isPropertyAccessExpression(node) || ts.isIdentifier(node))
168
- && !(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)
169
- && !(node.parent && (ts.isImportSpecifier(node.parent) || ts.isExportSpecifier(node.parent) || ts.isImportClause(node.parent) || ts.isNamespaceImport(node.parent)))
170
- if (isChainTop) {
171
- const p = sdkPath(node)
172
- if (p && p.length) {
173
- let name = p.join('.')
174
- const call = node.parent && ts.isCallExpression(node.parent) && node.parent.expression === node ? node.parent : null
175
-
176
- // A call that only changed name.
177
- if (idx.renames.has(name)) {
178
- const to = idx.renames.get(name)
179
- const [fromHead, toHead] = [name.split('.')[0], to.split('.')[0]]
180
- // The part that changes is the first one: `product` in product.get, or the whole of a type's name.
181
- let head = node
182
- for (let i = p.length; i > 1 && ts.isPropertyAccessExpression(head); i--) head = head.expression
183
- while (ts.isParenthesizedExpression(head) || ts.isNonNullExpression(head) || ts.isAsExpression(head)) head = head.expression
184
- if (ts.isPropertyAccessExpression(head) && head.name.text === fromHead) {
185
- edits.push({ start: head.name.getStart(sf), end: head.name.getEnd(), text: toHead }) // SL.product → SL.products
186
- } else if (ts.isIdentifier(head) && imports.has(symbolOf(head)) && imports.get(symbolOf(head)).imported === fromHead) {
187
- const sym = symbolOf(head)
188
- renameRefs.set(sym, [...(renameRefs.get(sym) || []), { id: head, to: toHead }])
189
- } else {
190
- push('by-hand', node, name, { to, note: `Renamed to \`${to}\`, but reached here through another name: rename it by hand.` })
191
- }
192
- name = to
193
- }
194
-
195
- const key = name + '@' + node.getStart(sf)
196
- if (!seen.has(key)) {
197
- seen.add(key)
198
- if (idx.hold.has(name)) push('hold', node, name, { note: idx.hold.get(name).why })
199
- const gone = idx.removed.get(name)
200
- if (gone) push('removed', node, name, { to: gone.to || null, note: gone.note || '' })
201
- const list = idx.lists.get(name)
202
- if (list) {
203
- const keys = call ? objectKeys(call) : new Set()
204
- const passes = (list.optionsRemoved || []).filter((o) => keys.has(o.split('.')[0]))
205
- push('list', node, name, { before: list.before, after: list.after, paged: !!list.paged, passes, called: !!call, note: list.note || '' })
206
- }
207
- for (const opt of idx.options.get(name) || []) {
208
- if (typeof opt.argument === 'number') {
209
- // An argument that went: drop it when it is the last one passed.
210
- if (call && call.arguments.length === opt.argument + 1) {
211
- const arg = call.arguments[opt.argument]
212
- const from = opt.argument === 0 ? arg.getFullStart() : call.arguments[opt.argument - 1].getEnd()
213
- edits.push({ start: from, end: arg.getEnd(), text: '' })
214
- } else if (call && call.arguments.length > opt.argument + 1) {
215
- push('option', node, name, { option: opt.option, note: opt.note })
216
- }
217
- } else if (call && objectKeys(call).has(opt.option)) {
218
- push('option', node, name, { option: opt.option, note: opt.note })
219
- } else if (call && call.arguments.some((a) => !ts.isObjectLiteralExpression(a) && !ts.isStringLiteral(a) && !ts.isNumericLiteral(a) && a.kind !== ts.SyntaxKind.TrueKeyword && a.kind !== ts.SyntaxKind.FalseKeyword
220
- // An id or the admin flag is not an options object: `facets.list(collectionId)` passes no options.
221
- && !(ts.isIdentifier(a) && /(Id|Ids|^id|^admin|^isAdmin)$/.test(a.text)))) {
222
- // Options built somewhere else: can't see inside from here.
223
- push('option-check', node, name, { option: opt.option, note: opt.note })
224
- }
225
- }
226
- }
227
- }
228
- }
229
- ts.forEachChild(node, visit)
230
- }
231
- visit(sf)
232
-
233
- // A namespace that changed name (product → products): any use of the old one that the script couldn't
234
- // rename and the table doesn't name (passed as a value, say) still has to be found by someone.
235
- const goneHeads = new Map()
236
- for (const [from, to] of idx.renames) if (from.includes('.') && from.split('.')[0] !== to.split('.')[0]) goneHeads.set(from.split('.')[0], to.split('.')[0])
237
- for (const [sym, all] of refs) {
238
- const imp = imports.get(sym)
239
- if (!goneHeads.has(imp.imported)) continue
240
- const renamed = new Set((renameRefs.get(sym) || []).map((u) => u.id))
241
- for (const id of all) {
242
- if (renamed.has(id)) continue
243
- const line = lineOf(id)
244
- if (work.some((w) => w.line === line && (w.kind === 'removed' || w.kind === 'by-hand'))) continue
245
- push('by-hand', id, imp.imported, { to: goneHeads.get(imp.imported), note: `The \`${imp.imported}\` namespace is \`${goneHeads.get(imp.imported)}\` in SDK 3. This use isn't a plain call, so change it by hand.` })
246
- }
247
- }
248
-
249
- // 3. Imports whose uses were renamed: rename the import to match.
250
- const declared = (name) => {
251
- // Is `name` already something else in this file (a variable, a parameter, another import)?
252
- let clash = false
253
- const look = (n) => {
254
- if (clash) return
255
- if (ts.isIdentifier(n) && n.text === name) {
256
- const isMemberName = n.parent && ((ts.isPropertyAccessExpression(n.parent) && n.parent.name === n)
257
- || ((ts.isPropertyAssignment(n.parent) || ts.isPropertySignature(n.parent) || ts.isPropertyDeclaration(n.parent) || ts.isMethodDeclaration(n.parent) || ts.isMethodSignature(n.parent)) && n.parent.name === n)
258
- || (ts.isBindingElement(n.parent) && n.parent.propertyName === n)
259
- || (ts.isJsxAttribute(n.parent) && n.parent.name === n)
260
- || ((ts.isImportSpecifier(n.parent) || ts.isExportSpecifier(n.parent)) && n.parent.propertyName === n))
261
- if (!isMemberName) {
262
- const sym = symbolOf(n)
263
- const imp = sym && imports.get(sym)
264
- if (!(imp && imp.imported === name && imp.local === name)) clash = true
265
- }
266
- }
267
- ts.forEachChild(n, look)
268
- }
269
- look(sf)
270
- return clash
271
- }
272
-
273
- const specEdits = new Map() // import declaration → { remove: Set<spec>, rename: Map<spec, text>, add: Set<text> }
274
- const planFor = (decl) => { if (!specEdits.has(decl)) specEdits.set(decl, { remove: new Set(), rename: new Map(), add: new Set() }); return specEdits.get(decl) }
275
-
276
- for (const [sym, uses] of renameRefs) {
277
- const imp = imports.get(sym)
278
- const to = uses[0].to
279
- const all = refs.get(sym) || []
280
- const everyUse = all.length === uses.length
281
- const already = [...imports.values()].find((i) => i.imported === to) // the new name is imported too
282
- const aliased = imp.local !== imp.imported
283
-
284
- if (aliased) {
285
- // import { product as p }: the uses keep their name; only what it points at changes.
286
- if (!everyUse) { for (const u of uses) push('by-hand', u.id, imp.imported, { to, note: `\`${imp.imported}\` is \`${to}\` in SDK 3, but \`${imp.local}\` is also used here for something \`${to}\` doesn't do the same way. Change the import by hand.` }); continue }
287
- planFor(imp.decl).rename.set(imp.spec, `${to} as ${imp.local}`)
288
- continue
289
- }
290
-
291
- let local = to
292
- if (already) local = already.local
293
- else if (declared(to)) {
294
- // `const products = await product.list()` is everywhere: the SDK's name can't also be `products` here.
295
- local = to + 'Api'
296
- if (declared(local)) { for (const u of uses) push('by-hand', u.id, imp.imported, { to, note: `\`${imp.imported}\` is \`${to}\` in SDK 3, but both \`${to}\` and \`${local}\` already mean something else in this file. Rename by hand.` }); continue }
297
- }
298
- for (const u of uses) edits.push({ start: u.id.getStart(sf), end: u.id.getEnd(), text: local })
299
- const plan = planFor(imp.decl)
300
- if (already) { if (everyUse) plan.remove.add(imp.spec) }
301
- else if (everyUse) plan.rename.set(imp.spec, local === to ? to : `${to} as ${local}`)
302
- else plan.add.add(local === to ? to : `${to} as ${local}`)
303
- }
304
-
305
- // Each import is changed in place, name by name, so its layout stays as the author had it.
306
- for (const [decl, plan] of specEdits) {
307
- const nb = decl.importClause.namedBindings
308
- const els = [...nb.elements]
309
- const kept = els.filter((s) => !plan.remove.has(s))
310
- if (!kept.length && !plan.add.size) {
311
- // Nothing left to import from this line.
312
- if (decl.importClause.name) edits.push({ start: decl.importClause.name.getEnd(), end: nb.getEnd(), text: '' })
313
- else { let end = decl.getEnd(); if (text.slice(end, end + 2) === '\r\n') end += 2; else if (text[end] === '\n') end += 1; edits.push({ start: decl.getStart(sf), end, text: '' }) }
314
- continue
315
- }
316
- els.forEach((spec, i) => {
317
- if (plan.remove.has(spec)) {
318
- // With the comma that belongs to it: the one after, or for the last name the one before.
319
- if (i < els.length - 1) edits.push({ start: spec.getStart(sf), end: els[i + 1].getStart(sf), text: '' })
320
- else edits.push({ start: i > 0 ? els[i - 1].getEnd() : spec.getStart(sf), end: spec.getEnd(), text: '' })
321
- } else if (plan.rename.has(spec)) {
322
- edits.push({ start: spec.getStart(sf), end: spec.getEnd(), text: (spec.isTypeOnly ? 'type ' : '') + plan.rename.get(spec) })
323
- }
324
- })
325
- const names = new Set(kept.map((s) => (plan.rename.has(s) ? plan.rename.get(s) : s.getText(sf))))
326
- const extra = [...plan.add].filter((a) => !names.has(a))
327
- if (extra.length) { const last = kept[kept.length - 1]; edits.push({ start: last.getEnd(), end: last.getEnd(), text: ', ' + extra.join(', ') }) }
328
- }
329
-
330
- // 4. Things only a search can hint at.
331
- const hint = (re, name, note) => {
332
- let m
333
- const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g')
334
- while ((m = g.exec(text))) work.push({ kind: 'check', file: rel, line: text.slice(0, m.index).split('\n').length, name, note })
335
- }
336
- // A code compared with something that isn't UPPER_SNAKE: 'segments.list.failed', 'notFound'.
337
- hint(/\b(?:errorCode|details\??\.error(?:Code)?)\s*(?:===|!==|==|!=)\s*['"`](?![A-Z0-9_]+['"`])[^'"`]+['"`]/, 'error codes',
338
- 'Compares an error code with a dotted or camel-case string. Codes are UPPER_SNAKE in SDK 3 (`segments.list.failed` is `SEGMENTS_LIST_FAILED`); read it from `error.errorCode`.')
339
- hint(/\bdetails\??\.error(?:Code)?\b(?!\s*(?:===|!==|==|!=))/, 'error codes', 'Reads the code from `details`. Use `error.errorCode`.')
340
- hint(/['"]@proveanything\/smartlinks['"]\s*:\s*['"]SL['"]/, 'shared dependencies',
341
- 'The SDK\'s window global is written out here as `SL`. In a build for SDK 3 it is `SL3`: take the globals from `SHARED_DEPENDENCIES` so this can\'t drift.')
342
- hint(/\bwindow\.SL\b(?!3)/, 'shared dependencies', 'Reads `window.SL`, which stays SDK 2. A component built on SDK 3 gets the SDK from its import (or `window.SL3`).')
343
-
344
- return { edits, work }
345
- }
346
-
347
- function applyEdits(text, edits) {
348
- const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end)
349
- let out = text
350
- let last = Infinity
351
- for (const e of sorted) {
352
- if (e.end > last) continue // overlapping: keep the later one in the file, skip this
353
- out = out.slice(0, e.start) + e.text + out.slice(e.end)
354
- last = e.start
355
- }
356
- return out
357
- }
358
-
359
- // ── the whole app ────────────────────────────────────────────────────────────────────────────────
360
-
361
- /**
362
- * Plan (and with `write: true`, make) the move.
363
- * Returns { table, files: [{ file, edits }], work: [...], manifest, packages, changed: [...paths] }.
364
- */
365
- export function upgradeApp({ dir, major = '3', write = false, ts = null } = {}) {
366
- const appDir = path.resolve(dir || process.cwd())
367
- const table = loadTable(major)
368
- const idx = indexTable(table)
369
- ts = ts || loadTypeScript(appDir)
370
- if (!ts) throw new Error('TypeScript was not found. Install it in the app (npm install -D typescript) and run again.')
371
-
372
- const files = sourceFiles(appDir)
373
- const program = ts.createProgram(files, {
374
- allowJs: true, checkJs: false, noResolve: true, noLib: true, skipLibCheck: true,
375
- jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, types: [],
376
- })
377
- const checker = program.getTypeChecker()
378
-
379
- const result = { table, dir: appDir, files: [], work: [], changed: [], manifest: null, packages: [] }
380
- for (const file of files) {
381
- const sf = program.getSourceFile(file)
382
- if (!sf || !/smartlinks|\bSL3?\b|errorCode/.test(sf.text)) continue
383
- const rel = path.relative(appDir, file).replace(/\\/g, '/')
384
- const { edits, work } = analyseFile(ts, checker, sf, idx, rel)
385
- result.work.push(...work)
386
- if (edits.length) {
387
- result.files.push({ file: rel, edits: edits.length })
388
- if (write) { fs.writeFileSync(file, applyEdits(sf.text, edits)); result.changed.push(rel) }
389
- }
390
- }
391
-
392
- // The manifest says which shared-dependency contract the build is for.
393
- const contract = table.sharedDependencies
394
- for (const rel of ['public/app.manifest.json', 'app.manifest.json']) {
395
- const p = path.join(appDir, rel)
396
- if (!contract || !fs.existsSync(p)) continue
397
- const raw = fs.readFileSync(p, 'utf8')
398
- const m = /("sharedDependencies"\s*:\s*")([^"]+)(")/.exec(raw)
399
- if (!m) break
400
- result.manifest = { file: rel, from: m[2], to: contract.to }
401
- if (m[2] !== contract.to && write) { fs.writeFileSync(p, raw.replace(m[0], m[1] + contract.to + m[3])); result.changed.push(rel) }
402
- break
403
- }
404
-
405
- // Other SmartLinks packages that use the SDK must be versions built for this major.
406
- for (const name of ['@proveanything/smartlinks-utils-ui', '@proveanything/smartlinks-auth-ui']) {
407
- try {
408
- const pkg = JSON.parse(fs.readFileSync(path.join(appDir, 'node_modules', name, 'package.json'), 'utf8'))
409
- const range = { ...(pkg.dependencies || {}), ...(pkg.peerDependencies || {}) }['@proveanything/smartlinks']
410
- const ok = !range || range === '*' || new RegExp(`(^|[^\\d.])${major}(\\.|\\b)`).test(range) || /^>=/.test(range.trim())
411
- result.packages.push({ name, version: pkg.version, range: range || null, ok })
412
- } catch { /* not installed */ }
413
- }
414
-
415
- result.fields = idx.fields
416
- result.behaviour = idx.behaviour
417
- return result
418
- }
419
-
420
- // ── the report ───────────────────────────────────────────────────────────────────────────────────
421
-
422
- const plural = (n, one, many = one + 's') => `${n} ${n === 1 ? one : many}`
423
-
424
- /** The plan as Markdown: what the script did (or would do), then the work left, file by file. */
425
- export function formatReport(result, { write = false } = {}) {
426
- const { table, work } = result
427
- const out = []
428
- const major = table.sdk.to
429
- out.push(`# Moving to SDK ${major}`, '')
430
-
431
- const edits = result.files.reduce((n, f) => n + f.edits, 0)
432
- const manifestChange = result.manifest && result.manifest.from !== result.manifest.to
433
- out.push(`## ${write ? 'Done by the script' : 'What the script will change (run again with --write)'}`, '')
434
- if (!edits && !manifestChange) out.push('Nothing mechanical to change.', '')
435
- for (const f of result.files) out.push(`- \`${f.file}\`: ${plural(f.edits, 'edit')} (renamed calls, dropped arguments, imports)`)
436
- if (manifestChange) out.push(`- \`${result.manifest.file}\`: \`sharedDependencies\` ${result.manifest.from} → ${result.manifest.to}`)
437
- if (edits || manifestChange) out.push('')
438
-
439
- const of = (kind) => work.filter((w) => w.kind === kind)
440
- const where = (w) => `\`${w.file}:${w.line}\``
441
-
442
- const hold = of('hold')
443
- if (hold.length) {
444
- out.push('## Leave these as they are', '', hold[0].note, '')
445
- for (const w of hold) out.push(`- ${where(w)} \`${w.name}\``)
446
- out.push('')
447
- }
448
-
449
- const bad = result.packages.filter((p) => !p.ok)
450
- if (bad.length) {
451
- out.push('## Packages to update first', '')
452
- for (const p of bad) out.push(`- \`${p.name}\` ${p.version} is built for SDK \`${p.range}\`. Install a version built for SDK ${major}, or it will read the old shapes.`)
453
- out.push('')
454
- }
455
-
456
- const removed = [...of('removed'), ...of('by-hand')]
457
- if (removed.length) {
458
- out.push(`## Calls to replace (${removed.length})`, '')
459
- for (const w of removed) out.push(`- ${where(w)} \`${w.name}\`${w.to ? ` → \`${w.to}\`` : ''}. ${w.note}`)
460
- out.push('')
461
- }
462
-
463
- const options = [...of('option'), ...of('option-check')]
464
- if (options.length) {
465
- out.push(`## Options that went (${options.length})`, '')
466
- for (const w of options) out.push(`- ${where(w)} \`${w.name}\` ${w.kind === 'option' ? 'passes' : 'may pass'} \`${w.option}\`. ${w.note}`)
467
- out.push('')
468
- }
469
-
470
- const lists = of('list')
471
- if (lists.length) {
472
- out.push(`## Lists whose result changed (${lists.length})`, '',
473
- 'Each of these now returns `{ items, nextCursor, count? }`. At each place: read the list from `.items`,',
474
- 'a total from `.count`, "is there more" from `.nextCursor !== null`, and page with `cursor`, not `offset` or `page`.', '')
475
- const byFile = new Map()
476
- for (const w of lists) byFile.set(w.file, [...(byFile.get(w.file) || []), w])
477
- for (const [file, items] of byFile) {
478
- out.push(`### \`${file}\``, '')
479
- for (const w of items) {
480
- const bits = [`was \`${w.before}\``]
481
- if (w.passes.length) bits.push(`**passes ${w.passes.map((p) => '`' + p + '`').join(', ')}**, which is gone`)
482
- if (!w.paged) bits.push('not paged')
483
- if (!w.called) bits.push('passed as a value, not called here: follow it to where the result is read')
484
- if (w.note) bits.push(w.note)
485
- out.push(`- line ${w.line} \`${w.name}\`: ${bits.join('; ')}`)
486
- }
487
- out.push('')
488
- }
489
- }
490
-
491
- const checks = of('check')
492
- if (checks.length) {
493
- out.push(`## Check by hand (${checks.length})`, '')
494
- const seen = new Set()
495
- for (const w of checks) { const k = w.file + ':' + w.line + w.note; if (seen.has(k)) continue; seen.add(k); out.push(`- ${where(w)} ${w.note}`) }
496
- out.push('')
497
- }
498
-
499
- out.push('## What no script can see', '')
500
- for (const b of result.behaviour) out.push(`- **${b.name}.** ${b.note}`)
501
- for (const f of result.fields) out.push(`- **\`${f.name}\`** (a field).${f.to ? ` Use \`${f.to}\`.` : ''} ${f.note}`)
502
- out.push('', `Everything above is explained in \`docs/${path.basename(table.guide)}\` in this package.`, '')
503
- return out.join('\n')
504
- }
505
-
506
- /** One line for a log. */
507
- export function summary(result) {
508
- const n = (k) => result.work.filter((w) => w.kind === k).length
509
- return `${plural(result.files.reduce((a, f) => a + f.edits, 0), 'mechanical edit')} in ${plural(result.files.length, 'file')}; `
510
- + `left to do: ${plural(n('list'), 'list call')}, ${plural(n('removed') + n('by-hand'), 'call')} to replace, ${plural(n('option') + n('option-check'), 'option')}, ${plural(n('check'), 'check')}`
511
- + (n('hold') ? `; ${plural(n('hold'), 'call')} to leave alone` : '')
512
- }
1
+ // =============================================================================
2
+ // Moving an app to a new major of the SDK: what a script can safely do, and a list of everything else.
3
+ //
4
+ // Reads upgrade/<major>.json (the same table docs/upgrading-to-<major>.md is filled from) and the app's
5
+ // source, and:
6
+ // 1. plans the MECHANICAL edits: a call that only changed name, an argument that went, the manifest's
7
+ // shared-dependency contract. Nothing that changes what the code means.
8
+ // 2. lists every other place the table says needs a person or an agent: each call to a list whose
9
+ // shape changed, each removed call, each option that went, each thing to check at run time.
10
+ //
11
+ // It finds SDK calls by what a name is BOUND to, not by its spelling: `product.get(…)` is only an SDK
12
+ // call where `product` is the SDK's export (an import, `SL.product`, or taken from one of those). A
13
+ // local variable that happens to be called `product` is never touched.
14
+ //
15
+ // Used by scripts/upgrade.mjs (the `smartlinks-upgrade` command) and by the SDK's tests.
16
+ // =============================================================================
17
+
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import { createRequire } from 'node:module'
21
+ import { fileURLToPath } from 'node:url'
22
+
23
+ const here = path.dirname(fileURLToPath(import.meta.url))
24
+ const SDK = /^@proveanything\/smartlinks(\/.*)?$/
25
+ const SOURCE = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/
26
+ const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', '.git', '.next', '.output', '.vite', '.turbo', 'coverage', '.forge', '.lovable'])
27
+
28
+ /** The upgrade table for a major, from this package. */
29
+ export function loadTable(major = '3') {
30
+ return JSON.parse(fs.readFileSync(path.join(here, '..', '..', 'upgrade', `${major}.json`), 'utf8'))
31
+ }
32
+
33
+ /** TypeScript's parser: the app's own copy if it has one, else whatever this package can reach. */
34
+ export function loadTypeScript(appDir) {
35
+ for (const from of [path.join(appDir, 'package.json'), path.join(here, 'package.json')]) {
36
+ try { return createRequire(from)('typescript') } catch { /* try the next place */ }
37
+ }
38
+ return null
39
+ }
40
+
41
+ function sourceFiles(appDir) {
42
+ const out = []
43
+ const walk = (dir, depth) => {
44
+ let entries = []
45
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
46
+ for (const e of entries) {
47
+ const p = path.join(dir, e.name)
48
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.') && depth < 12) walk(p, depth + 1) }
49
+ else if (SOURCE.test(e.name) && !e.name.endsWith('.d.ts')) out.push(p)
50
+ }
51
+ }
52
+ walk(appDir, 0)
53
+ return out
54
+ }
55
+
56
+ // ── the table, indexed ───────────────────────────────────────────────────────────────────────────
57
+
58
+ function indexTable(table) {
59
+ const renames = new Map() // old full name → new full name, mechanical only
60
+ const removed = new Map() // name → entry (also renames a script must not do)
61
+ const lists = new Map()
62
+ const options = new Map() // name → [entries]
63
+ const fields = [] // entries about a field of a type: only a person or a type-check finds these
64
+ for (const c of table.changes) {
65
+ if (c.kind === 'renamed' && c.mechanical) renames.set(c.name, c.to)
66
+ else if (c.kind === 'renamed' || c.kind === 'removed') {
67
+ if (c.what === 'field') fields.push(c)
68
+ else removed.set(c.name, c)
69
+ } else if (c.kind === 'list') lists.set(c.name, c)
70
+ else if (c.kind === 'option') options.set(c.name, [...(options.get(c.name) || []), c])
71
+ }
72
+ const hold = new Map()
73
+ for (const h of table.hold || []) for (const n of h.names || []) hold.set(n, h)
74
+ return { renames, removed, lists, options, fields, hold, behaviour: table.changes.filter((c) => c.kind === 'behaviour') }
75
+ }
76
+
77
+ // ── one file ─────────────────────────────────────────────────────────────────────────────────────
78
+
79
+ function analyseFile(ts, checker, sf, idx, rel) {
80
+ const text = sf.text
81
+ const edits = [] // { start, end, text }
82
+ const work = [] // { kind, name, line, note, ... }
83
+ const lineOf = (node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1
84
+ const push = (kind, node, name, extra = {}) => work.push({ kind, file: rel, line: lineOf(node), name, ...extra })
85
+ // `// sl-upgrade: ok <why>` on the line, or the line above, says a person has looked at this place and it
86
+ // is right as it is (the first page is all that's wanted; the options come from elsewhere and carry a
87
+ // limit). It settles what only a person can judge; it never excuses a call that no longer exists.
88
+ const lines = text.split('\n')
89
+ const MARK = /sl-upgrade:\s*ok\b/i
90
+ const markedAt = (line) => MARK.test(lines[line - 1] || '') || MARK.test(lines[line - 2] || '')
91
+ /** Is this node inside the page function handed to `all(…)` or `each(…)`? */
92
+ const insideWalk = (node) => {
93
+ for (let n = node.parent; n; n = n.parent) {
94
+ if (!ts.isCallExpression(n)) continue
95
+ const callee = n.expression
96
+ const name = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : ''
97
+ if ((name === 'all' || name === 'each') && n.arguments.some((a) => a.pos <= node.pos && node.end <= a.end)) return true
98
+ }
99
+ return false
100
+ }
101
+
102
+ // 1. What the SDK's names are bound to in this file.
103
+ const imports = new Map() // symbol → { imported, local, spec, decl }
104
+ const namespaces = new Set() // symbols of `import * as X` / default imports of the SDK
105
+ for (const st of sf.statements) {
106
+ if (ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier) && SDK.test(st.moduleSpecifier.text) && st.importClause) {
107
+ const clause = st.importClause
108
+ if (clause.name) { const s = checker.getSymbolAtLocation(clause.name); if (s) namespaces.add(s) }
109
+ const nb = clause.namedBindings
110
+ if (nb && ts.isNamespaceImport(nb)) { const s = checker.getSymbolAtLocation(nb.name); if (s) namespaces.add(s) }
111
+ if (nb && ts.isNamedImports(nb)) {
112
+ for (const spec of nb.elements) {
113
+ const s = checker.getSymbolAtLocation(spec.name)
114
+ if (s) imports.set(s, { imported: (spec.propertyName || spec.name).text, local: spec.name.text, spec, decl: st })
115
+ }
116
+ }
117
+ }
118
+ // export { product } from '@proveanything/smartlinks'
119
+ if (ts.isExportDeclaration(st) && st.moduleSpecifier && ts.isStringLiteral(st.moduleSpecifier) && SDK.test(st.moduleSpecifier.text) && st.exportClause && ts.isNamedExports(st.exportClause)) {
120
+ for (const spec of st.exportClause.elements) {
121
+ const name = (spec.propertyName || spec.name).text
122
+ const hit = [...idx.renames.keys(), ...idx.removed.keys()].find((n) => n === name || n.startsWith(name + '.'))
123
+ if (hit) push('by-hand', spec, name, { note: `Re-exported from the SDK here. \`${name}\` is ${idx.renames.has(hit) ? 'renamed' : 'gone'} in SDK 3: change the re-export, then whatever imports it from this file.` })
124
+ }
125
+ }
126
+ }
127
+
128
+ const symbolOf = (id) => {
129
+ if (id.parent && ts.isShorthandPropertyAssignment(id.parent) && id.parent.name === id) return checker.getShorthandAssignmentValueSymbol(id.parent)
130
+ return checker.getSymbolAtLocation(id)
131
+ }
132
+
133
+ /** The SDK name an expression stands for (['products', 'list']), [] for the SDK itself, null for anything else. */
134
+ /**
135
+ * Is this SDK call hidden from the type-check? It is when the SDK was cast to `any` on the way to it
136
+ * (`(SL as any).batch.list(…)`), reached through a name declared `any` (`const facets: any = SL.facets`),
137
+ * or its result is put straight into something declared `any` (`const res: any = await x.list()`).
138
+ * Such a call compiles whatever it does with the answer, so the type-check finishes the pass without it.
139
+ */
140
+ const isAny = (typeNode) => !!typeNode && typeNode.kind === ts.SyntaxKind.AnyKeyword
141
+ const hiddenFromTypes = (node) => {
142
+ for (let n = node; n; ) {
143
+ if (ts.isAsExpression(n) && isAny(n.type)) return true
144
+ if (ts.isPropertyAccessExpression(n) || ts.isParenthesizedExpression(n) || ts.isNonNullExpression(n) || ts.isAsExpression(n)) { n = n.expression; continue }
145
+ if (ts.isIdentifier(n)) {
146
+ const sym = symbolOf(n)
147
+ const decl = sym && sym.valueDeclaration
148
+ if (decl && ts.isVariableDeclaration(decl) && isAny(decl.type)) return true
149
+ }
150
+ break
151
+ }
152
+ // The answer goes straight into an `any`.
153
+ let up = node.parent
154
+ while (up && (ts.isCallExpression(up) || ts.isAwaitExpression(up) || ts.isParenthesizedExpression(up))) up = up.parent
155
+ if (up && ts.isAsExpression(up) && isAny(up.type)) return true
156
+ if (up && ts.isVariableDeclaration(up) && isAny(up.type)) return true
157
+ return false
158
+ }
159
+
160
+ const sdkPath = (node, depth = 0) => {
161
+ if (!node || depth > 8) return null
162
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node) || ts.isAsExpression(node)) return sdkPath(node.expression, depth + 1)
163
+ if (ts.isIdentifier(node)) {
164
+ const sym = symbolOf(node)
165
+ if (sym && imports.has(sym)) return [imports.get(sym).imported]
166
+ if (sym && namespaces.has(sym)) return []
167
+ // const { product } = SL · const records = SL.app.records
168
+ const decl = sym && sym.declarations && sym.declarations[0]
169
+ if (decl && ts.isBindingElement(decl) && ts.isObjectBindingPattern(decl.parent) && ts.isVariableDeclaration(decl.parent.parent) && decl.parent.parent.initializer) {
170
+ const base = sdkPath(decl.parent.parent.initializer, depth + 1)
171
+ const key = decl.propertyName || decl.name
172
+ if (base && ts.isIdentifier(key)) return [...base, key.text]
173
+ }
174
+ if (decl && ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name) && decl.initializer && decl.initializer !== node
175
+ && ts.isVariableDeclarationList(decl.parent) && (decl.parent.flags & ts.NodeFlags.Const)) {
176
+ const base = sdkPath(decl.initializer, depth + 1)
177
+ if (base) return base
178
+ }
179
+ // The SDK handed over by a host is called SL by convention (window.SL, host.SL, a prop named SL).
180
+ if (node.text === 'SL' || node.text === 'SL3') return []
181
+ return null
182
+ }
183
+ if (ts.isPropertyAccessExpression(node)) {
184
+ if (node.name.text === 'SL' || node.name.text === 'SL3') return []
185
+ const base = sdkPath(node.expression, depth + 1)
186
+ return base ? [...base, node.name.text] : null
187
+ }
188
+ return null
189
+ }
190
+
191
+ // 2. Every use of an SDK name.
192
+ const refs = new Map() // import symbol → [identifier]
193
+ const renameRefs = new Map() // import symbol → [{ id, to }]: uses a script may rename
194
+ const seen = new Set() // "name@pos": one entry per place
195
+
196
+ const objectKeys = (call) => {
197
+ const keys = new Set()
198
+ const named = (p) => p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name))
199
+ for (const a of call.arguments || []) {
200
+ if (!ts.isObjectLiteralExpression(a)) continue
201
+ for (const p of a.properties) {
202
+ if (!named(p)) continue
203
+ keys.add(p.name.text)
204
+ // One level down, for options that sat inside another (`query.search`, `page.offset`):
205
+ // the keys written out, or "anything" when the inner object isn't written here.
206
+ if (ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {
207
+ for (const q of p.initializer.properties) { if (named(q)) keys.add(p.name.text + '.' + q.name.text); else keys.add(p.name.text + '.*') }
208
+ } else keys.add(p.name.text + '.*')
209
+ }
210
+ }
211
+ return keys
212
+ }
213
+ /** Does a call's options object carry `option` (which may be `outer.inner`)? */
214
+ const carries = (keys, option) => {
215
+ if (!option.includes('.')) return keys.has(option)
216
+ return keys.has(option) || keys.has(option.split('.')[0] + '.*')
217
+ }
218
+
219
+ const visit = (node) => {
220
+ if (ts.isIdentifier(node)) {
221
+ const sym = symbolOf(node)
222
+ const imp = sym && imports.get(sym)
223
+ if (imp && node !== imp.spec.name && node !== imp.spec.propertyName) refs.set(sym, [...(refs.get(sym) || []), node])
224
+ }
225
+
226
+ const isChainTop = (ts.isPropertyAccessExpression(node) || ts.isIdentifier(node))
227
+ && !(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)
228
+ && !(node.parent && (ts.isImportSpecifier(node.parent) || ts.isExportSpecifier(node.parent) || ts.isImportClause(node.parent) || ts.isNamespaceImport(node.parent)))
229
+ if (isChainTop) {
230
+ const p = sdkPath(node)
231
+ if (p && p.length) {
232
+ let name = p.join('.')
233
+ const call = node.parent && ts.isCallExpression(node.parent) && node.parent.expression === node ? node.parent : null
234
+
235
+ // A call that only changed name.
236
+ if (idx.renames.has(name)) {
237
+ const to = idx.renames.get(name)
238
+ const [fromHead, toHead] = [name.split('.')[0], to.split('.')[0]]
239
+ const [fromLast, toLast] = [name.split('.').pop(), to.split('.').pop()]
240
+ // The last part changed (jobs.listJobs → jobs.list, async.enqueueAsyncJob → jobs.enqueue).
241
+ if (p.length > 1 && fromLast !== toLast && ts.isPropertyAccessExpression(node) && node.name.text === fromLast) {
242
+ edits.push({ start: node.name.getStart(sf), end: node.name.getEnd(), text: toLast })
243
+ }
244
+ // The first part changed: `product` in product.get, or the whole of a type's name.
245
+ let head = node
246
+ for (let i = p.length; i > 1 && ts.isPropertyAccessExpression(head); i--) head = head.expression
247
+ while (ts.isParenthesizedExpression(head) || ts.isNonNullExpression(head) || ts.isAsExpression(head)) head = head.expression
248
+ if (fromHead === toHead) {
249
+ // Same namespace: only the function's name changed, and that is done above.
250
+ } else if (ts.isPropertyAccessExpression(head) && head.name.text === fromHead) {
251
+ edits.push({ start: head.name.getStart(sf), end: head.name.getEnd(), text: toHead }) // SL.product → SL.products
252
+ } else if (ts.isIdentifier(head) && imports.has(symbolOf(head)) && imports.get(symbolOf(head)).imported === fromHead) {
253
+ const sym = symbolOf(head)
254
+ renameRefs.set(sym, [...(renameRefs.get(sym) || []), { id: head, to: toHead }])
255
+ } else {
256
+ push('by-hand', node, name, { to, note: `Renamed to \`${to}\`, but reached here through another name: rename it by hand.` })
257
+ }
258
+ name = to
259
+ }
260
+
261
+ const key = name + '@' + node.getStart(sf)
262
+ if (!seen.has(key)) {
263
+ seen.add(key)
264
+ if (idx.hold.has(name)) push('hold', node, name, { note: idx.hold.get(name).why })
265
+ const gone = idx.removed.get(name)
266
+ if (gone) push('removed', node, name, { to: gone.to || null, note: gone.note || '' })
267
+ const list = idx.lists.get(name)
268
+ if (list) {
269
+ const keys = call ? objectKeys(call) : new Set()
270
+ const passes = (list.optionsRemoved || []).filter((o) => carries(keys, o))
271
+ // A list that used to return everything: has this call been decided? It has when it says how many
272
+ // it wants (`limit`), follows the pages (`cursor`, or it sits inside all() / each()), or is marked.
273
+ const line = lineOf(node)
274
+ const decided = !list.firstPageOnly ? null
275
+ : keys.has('cursor') ? 'follows the pages'
276
+ : keys.has('limit') ? 'says how many'
277
+ : insideWalk(node) ? 'inside all() / each()'
278
+ : markedAt(line) ? 'marked ok'
279
+ : false
280
+ // `any` hides the call from the type-check: it has to be gone through by hand, or the `any` removed.
281
+ const untyped = hiddenFromTypes(node) && !markedAt(line)
282
+ push('list', node, name, { before: list.before, after: list.after, paged: !!list.paged, firstPageOnly: !!list.firstPageOnly, decided, untyped, passes, called: !!call, note: list.note || '' })
283
+ }
284
+ for (const opt of idx.options.get(name) || []) {
285
+ if (typeof opt.argument === 'number') {
286
+ // An argument that went: drop it when it is the last one passed.
287
+ if (call && call.arguments.length === opt.argument + 1) {
288
+ const arg = call.arguments[opt.argument]
289
+ const from = opt.argument === 0 ? arg.getFullStart() : call.arguments[opt.argument - 1].getEnd()
290
+ edits.push({ start: from, end: arg.getEnd(), text: '' })
291
+ } else if (call && call.arguments.length > opt.argument + 1) {
292
+ push('option', node, name, { option: opt.option, note: opt.note })
293
+ }
294
+ } else if (call && objectKeys(call).has(opt.option)) {
295
+ push('option', node, name, { option: opt.option, note: opt.note })
296
+ } else if (call && call.arguments.some((a) => !ts.isObjectLiteralExpression(a) && !ts.isStringLiteral(a) && !ts.isNumericLiteral(a) && a.kind !== ts.SyntaxKind.TrueKeyword && a.kind !== ts.SyntaxKind.FalseKeyword
297
+ // An id or the admin flag is not an options object: `facets.list(collectionId)` passes no options.
298
+ && !(ts.isIdentifier(a) && /(Id|Ids|^id|^admin|^isAdmin)$/.test(a.text)))) {
299
+ // Options built somewhere else: can't see inside from here.
300
+ push('option-check', node, name, { option: opt.option, note: opt.note })
301
+ }
302
+ }
303
+ }
304
+ }
305
+ }
306
+ ts.forEachChild(node, visit)
307
+ }
308
+ visit(sf)
309
+
310
+ // A namespace that changed name (product → products): any use of the old one that the script couldn't
311
+ // rename and the table doesn't name (passed as a value, say) still has to be found by someone.
312
+ const goneHeads = new Map()
313
+ for (const [from, to] of idx.renames) if (from.includes('.') && from.split('.')[0] !== to.split('.')[0]) goneHeads.set(from.split('.')[0], to.split('.')[0])
314
+ for (const [sym, all] of refs) {
315
+ const imp = imports.get(sym)
316
+ if (!goneHeads.has(imp.imported)) continue
317
+ const renamed = new Set((renameRefs.get(sym) || []).map((u) => u.id))
318
+ for (const id of all) {
319
+ if (renamed.has(id)) continue
320
+ const line = lineOf(id)
321
+ if (work.some((w) => w.line === line && (w.kind === 'removed' || w.kind === 'by-hand'))) continue
322
+ push('by-hand', id, imp.imported, { to: goneHeads.get(imp.imported), note: `The \`${imp.imported}\` namespace is \`${goneHeads.get(imp.imported)}\` in SDK 3. This use isn't a plain call, so change it by hand.` })
323
+ }
324
+ }
325
+
326
+ // 3. Imports whose uses were renamed: rename the import to match.
327
+ const declared = (name) => {
328
+ // Is `name` already something else in this file (a variable, a parameter, another import)?
329
+ let clash = false
330
+ const look = (n) => {
331
+ if (clash) return
332
+ if (ts.isIdentifier(n) && n.text === name) {
333
+ const isMemberName = n.parent && ((ts.isPropertyAccessExpression(n.parent) && n.parent.name === n)
334
+ || ((ts.isPropertyAssignment(n.parent) || ts.isPropertySignature(n.parent) || ts.isPropertyDeclaration(n.parent) || ts.isMethodDeclaration(n.parent) || ts.isMethodSignature(n.parent)) && n.parent.name === n)
335
+ || (ts.isBindingElement(n.parent) && n.parent.propertyName === n)
336
+ || (ts.isJsxAttribute(n.parent) && n.parent.name === n)
337
+ || ((ts.isImportSpecifier(n.parent) || ts.isExportSpecifier(n.parent)) && n.parent.propertyName === n))
338
+ if (!isMemberName) {
339
+ const sym = symbolOf(n)
340
+ const imp = sym && imports.get(sym)
341
+ if (!(imp && imp.imported === name && imp.local === name)) clash = true
342
+ }
343
+ }
344
+ ts.forEachChild(n, look)
345
+ }
346
+ look(sf)
347
+ return clash
348
+ }
349
+
350
+ const specEdits = new Map() // import declaration → { remove: Set<spec>, rename: Map<spec, text>, add: Set<text> }
351
+ const planFor = (decl) => { if (!specEdits.has(decl)) specEdits.set(decl, { remove: new Set(), rename: new Map(), add: new Set() }); return specEdits.get(decl) }
352
+
353
+ for (const [sym, uses] of renameRefs) {
354
+ const imp = imports.get(sym)
355
+ const to = uses[0].to
356
+ const all = refs.get(sym) || []
357
+ const everyUse = all.length === uses.length
358
+ const already = [...imports.values()].find((i) => i.imported === to) // the new name is imported too
359
+ const aliased = imp.local !== imp.imported
360
+
361
+ if (aliased) {
362
+ // import { product as p }: the uses keep their name; only what it points at changes.
363
+ if (!everyUse) { for (const u of uses) push('by-hand', u.id, imp.imported, { to, note: `\`${imp.imported}\` is \`${to}\` in SDK 3, but \`${imp.local}\` is also used here for something \`${to}\` doesn't do the same way. Change the import by hand.` }); continue }
364
+ planFor(imp.decl).rename.set(imp.spec, `${to} as ${imp.local}`)
365
+ continue
366
+ }
367
+
368
+ let local = to
369
+ if (already) local = already.local
370
+ else if (declared(to)) {
371
+ // `const products = await product.list()` is everywhere: the SDK's name can't also be `products` here.
372
+ local = to + 'Api'
373
+ if (declared(local)) { for (const u of uses) push('by-hand', u.id, imp.imported, { to, note: `\`${imp.imported}\` is \`${to}\` in SDK 3, but both \`${to}\` and \`${local}\` already mean something else in this file. Rename by hand.` }); continue }
374
+ }
375
+ for (const u of uses) edits.push({ start: u.id.getStart(sf), end: u.id.getEnd(), text: local })
376
+ const plan = planFor(imp.decl)
377
+ if (already) { if (everyUse) plan.remove.add(imp.spec) }
378
+ else if (everyUse) plan.rename.set(imp.spec, local === to ? to : `${to} as ${local}`)
379
+ else plan.add.add(local === to ? to : `${to} as ${local}`)
380
+ }
381
+
382
+ // Each import is changed in place, name by name, so its layout stays as the author had it.
383
+ for (const [decl, plan] of specEdits) {
384
+ const nb = decl.importClause.namedBindings
385
+ const els = [...nb.elements]
386
+ const kept = els.filter((s) => !plan.remove.has(s))
387
+ if (!kept.length && !plan.add.size) {
388
+ // Nothing left to import from this line.
389
+ if (decl.importClause.name) edits.push({ start: decl.importClause.name.getEnd(), end: nb.getEnd(), text: '' })
390
+ else { let end = decl.getEnd(); if (text.slice(end, end + 2) === '\r\n') end += 2; else if (text[end] === '\n') end += 1; edits.push({ start: decl.getStart(sf), end, text: '' }) }
391
+ continue
392
+ }
393
+ els.forEach((spec, i) => {
394
+ if (plan.remove.has(spec)) {
395
+ // With the comma that belongs to it: the one after, or for the last name the one before.
396
+ if (i < els.length - 1) edits.push({ start: spec.getStart(sf), end: els[i + 1].getStart(sf), text: '' })
397
+ else edits.push({ start: i > 0 ? els[i - 1].getEnd() : spec.getStart(sf), end: spec.getEnd(), text: '' })
398
+ } else if (plan.rename.has(spec)) {
399
+ edits.push({ start: spec.getStart(sf), end: spec.getEnd(), text: (spec.isTypeOnly ? 'type ' : '') + plan.rename.get(spec) })
400
+ }
401
+ })
402
+ const names = new Set(kept.map((s) => (plan.rename.has(s) ? plan.rename.get(s) : s.getText(sf))))
403
+ const extra = [...plan.add].filter((a) => !names.has(a))
404
+ if (extra.length) { const last = kept[kept.length - 1]; edits.push({ start: last.getEnd(), end: last.getEnd(), text: ', ' + extra.join(', ') }) }
405
+ }
406
+
407
+ // 4. Things only a search can hint at.
408
+ const hint = (re, name, note) => {
409
+ let m
410
+ const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g')
411
+ while ((m = g.exec(text))) { const line = text.slice(0, m.index).split('\n').length; work.push({ kind: 'check', file: rel, line, name, note, ok: markedAt(line) }) }
412
+ }
413
+ // A code compared with something that isn't UPPER_SNAKE: 'segments.list.failed', 'notFound'.
414
+ hint(/\b(?:errorCode|details\??\.error(?:Code)?)\s*(?:===|!==|==|!=)\s*['"`](?![A-Z0-9_]+['"`])[^'"`]+['"`]/, 'error codes',
415
+ 'Compares an error code with a dotted or camel-case string. Codes are UPPER_SNAKE in SDK 3 (`segments.list.failed` is `SEGMENTS_LIST_FAILED`); read it from `error.errorCode`.')
416
+ hint(/\bdetails\??\.error(?:Code)?\b(?!\s*(?:===|!==|==|!=))/, 'error codes', 'Reads the code from `details`. Use `error.errorCode`.')
417
+ // The SDK named as the global `SL`: in a build config that is this app's own build; in the app's source
418
+ // it is a loader handing the SDK to OTHER apps' bundles, which is a different and bigger thing.
419
+ const inSource = /^src\//.test(rel)
420
+ hint(/['"]@proveanything\/smartlinks['"]\s*:\s*['"]SL['"]/, 'shared dependencies', inSource
421
+ ? 'This file gives the SDK to other apps\' bundles (a loader of its own). Once this app is on SDK 3, each app it embeds must still get the SDK IT was built for: SDK 2 (the host\'s `window.SL`) for a v7 manifest, SDK 3 for v8. Use the host\'s `EmbeddedWidget` prop instead of a loader of your own (the doctor says the same); the host chooses per app. Until then this app should stay on SDK 2.'
422
+ : 'The SDK\'s window global is written out here as `SL`. In a build for SDK 3 it is `SL3`: take the globals from `SHARED_DEPENDENCIES` so this can\'t drift.')
423
+ hint(/Object\.assign\(\s*window\b[^)]*\)|\bwindow\.SL\s*=(?!=)|\(window as any\)\.SL\s*=(?!=)/, 'shared dependencies',
424
+ 'Puts things on `window` for other bundles. `window.SL` belongs to the page\'s host and is SDK 2: an app on SDK 3 must never put its own SDK there, or every older app on the page gets SDK 3 and breaks. If this is a loader for embedded apps, use the host\'s `EmbeddedWidget` prop instead.')
425
+ hint(/\bwindow\.SL\b(?!3)/, 'shared dependencies', 'Reads `window.SL`, which stays SDK 2. A component built on SDK 3 gets the SDK from its import (or `window.SL3`).')
426
+
427
+ return { edits, work }
428
+ }
429
+
430
+ function applyEdits(text, edits) {
431
+ const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end)
432
+ let out = text
433
+ let last = Infinity
434
+ for (const e of sorted) {
435
+ if (e.end > last) continue // overlapping: keep the later one in the file, skip this
436
+ out = out.slice(0, e.start) + e.text + out.slice(e.end)
437
+ last = e.start
438
+ }
439
+ return out
440
+ }
441
+
442
+ // ── the whole app ────────────────────────────────────────────────────────────────────────────────
443
+
444
+ /**
445
+ * Plan (and with `write: true`, make) the move.
446
+ * Returns { table, files: [{ file, edits }], work: [...], manifest, packages, changed: [...paths] }.
447
+ */
448
+ export function upgradeApp({ dir, major = '3', write = false, ts = null } = {}) {
449
+ const appDir = path.resolve(dir || process.cwd())
450
+ const table = loadTable(major)
451
+ const idx = indexTable(table)
452
+ ts = ts || loadTypeScript(appDir)
453
+ if (!ts) throw new Error('TypeScript was not found. Install it in the app (npm install -D typescript) and run again.')
454
+
455
+ const files = sourceFiles(appDir)
456
+ const program = ts.createProgram(files, {
457
+ allowJs: true, checkJs: false, noResolve: true, noLib: true, skipLibCheck: true,
458
+ jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, types: [],
459
+ })
460
+ const checker = program.getTypeChecker()
461
+
462
+ const result = { table, dir: appDir, files: [], work: [], changed: [], manifest: null, packages: [] }
463
+ for (const file of files) {
464
+ const sf = program.getSourceFile(file)
465
+ if (!sf || !/smartlinks|\bSL3?\b|errorCode/.test(sf.text)) continue
466
+ const rel = path.relative(appDir, file).replace(/\\/g, '/')
467
+ const { edits, work } = analyseFile(ts, checker, sf, idx, rel)
468
+ result.work.push(...work)
469
+ if (edits.length) {
470
+ result.files.push({ file: rel, edits: edits.length })
471
+ if (write) { fs.writeFileSync(file, applyEdits(sf.text, edits)); result.changed.push(rel) }
472
+ }
473
+ }
474
+
475
+ // The manifest says which shared-dependency contract the build is for.
476
+ const contract = table.sharedDependencies
477
+ for (const rel of ['public/app.manifest.json', 'app.manifest.json']) {
478
+ const p = path.join(appDir, rel)
479
+ if (!contract || !fs.existsSync(p)) continue
480
+ const raw = fs.readFileSync(p, 'utf8')
481
+ const m = /("sharedDependencies"\s*:\s*")([^"]+)(")/.exec(raw)
482
+ if (!m) break
483
+ result.manifest = { file: rel, from: m[2], to: contract.to }
484
+ if (m[2] !== contract.to && write) { fs.writeFileSync(p, raw.replace(m[0], m[1] + contract.to + m[3])); result.changed.push(rel) }
485
+ break
486
+ }
487
+
488
+ // Other SmartLinks packages that use the SDK must be versions built for this major.
489
+ for (const name of ['@proveanything/smartlinks-utils-ui', '@proveanything/smartlinks-auth-ui']) {
490
+ try {
491
+ const pkg = JSON.parse(fs.readFileSync(path.join(appDir, 'node_modules', name, 'package.json'), 'utf8'))
492
+ const range = { ...(pkg.dependencies || {}), ...(pkg.peerDependencies || {}) }['@proveanything/smartlinks']
493
+ const ok = !range || range === '*' || new RegExp(`(^|[^\\d.])${major}(\\.|\\b)`).test(range) || /^>=/.test(range.trim())
494
+ result.packages.push({ name, version: pkg.version, range: range || null, ok })
495
+ } catch { /* not installed */ }
496
+ }
497
+
498
+ result.fields = idx.fields
499
+ result.behaviour = idx.behaviour
500
+ return result
501
+ }
502
+
503
+ // ── the passes ───────────────────────────────────────────────────────────────────────────────────
504
+
505
+ const plural = (n, one, many = one + 's') => `${n} ${n === 1 ? one : many}`
506
+
507
+ /**
508
+ * The move as a series of passes, in the order to do them. Each has the places still to change (`left`)
509
+ * and what decides it is finished (`judge`): this script, run again, or the app's own type-check.
510
+ * A pass the script judges is done when `left` is empty; do them in order, one at a time.
511
+ *
512
+ * automatic the renames and dropped arguments the script makes itself (--write)
513
+ * replace calls that no longer exist, and options that went: each needs a decision
514
+ * lists every list returns { items, nextCursor, count? } and takes the standard words: the
515
+ * type-check finds what is left (the script lists the calls, and judges the options)
516
+ * pages a list that used to return everything now returns one page: all of them, or a page?
517
+ * errors error codes compared as text, and the SDK read from window: found by search
518
+ */
519
+ export function passesOf(result, { write = false } = {}) {
520
+ const of = (kind) => result.work.filter((w) => w.kind === kind)
521
+ const edits = result.files.reduce((n, f) => n + f.edits, 0)
522
+ const manifestChange = !!(result.manifest && result.manifest.from !== result.manifest.to)
523
+ const lists = of('list')
524
+ const seen = new Set()
525
+ const checks = of('check').filter((w) => { const k = w.file + ':' + w.line + w.note; if (seen.has(k)) return false; seen.add(k); return true })
526
+ const pages = lists.filter((w) => w.firstPageOnly)
527
+ return [
528
+ {
529
+ id: 'automatic', title: 'Automatic changes', judge: 'script',
530
+ // After --write they are made: nothing is left unless the files could not be written.
531
+ left: write ? [] : [...result.files.map((f) => ({ file: f.file, edits: f.edits })), ...(manifestChange ? [{ file: result.manifest.file, edits: 1 }] : [])],
532
+ total: edits + (manifestChange ? 1 : 0),
533
+ how: 'Run `npx smartlinks-upgrade --write`.',
534
+ },
535
+ {
536
+ id: 'replace', title: 'Calls to replace and options that went', judge: 'script',
537
+ left: [...of('removed'), ...of('by-hand'), ...of('option'), ...of('option-check')],
538
+ how: 'Each is a call that no longer exists, or an option a call no longer takes. Replace it as the note says.',
539
+ },
540
+ {
541
+ id: 'lists', title: 'Lists: the new result and the standard words', judge: 'type-check',
542
+ // The script can see an option that is gone; whether `.items` is read is the type-check\'s to say.
543
+ left: lists.filter((w) => w.passes.length || w.untyped),
544
+ all: lists,
545
+ how: 'Read each list from `.items` (a total from `.count`, more from `.nextCursor`), page with `cursor`, and use `q`, `orderBy`, a date range and `expand`. Done when the app type-checks, no call here passes an option that is gone, and none is hidden from the type-check by `any`.',
546
+ },
547
+ {
548
+ id: 'pages', title: 'One page, or all of them', judge: 'script',
549
+ left: pages.filter((w) => w.decided === false),
550
+ decided: pages.filter((w) => w.decided),
551
+ how: 'Each of these returned everything in SDK 2 and returns 50 now. Where the app needs every item (it filters, counts, looks one up, fills a picker): `all((cursor) => theList(…, { limit: 200, cursor }))`. Where it shows a page: pass `limit` (and `cursor` for the next). Where the first 50 really is all that is wanted, or the options come from elsewhere: put `// sl-upgrade: ok <why>` on the line above.',
552
+ },
553
+ {
554
+ id: 'errors', title: 'Error codes and the SDK global', judge: 'script',
555
+ left: checks.filter((w) => !w.ok),
556
+ how: 'Found by search, so read each one. Where the code is right as it is, put `// sl-upgrade: ok <why>` on the line above.',
557
+ },
558
+ ]
559
+ }
560
+
561
+ /** Is there anything left in the passes this script judges (all of them, or just `only`)? */
562
+ export function leftToDo(result, { write = false, only = null } = {}) {
563
+ return passesOf(result, { write }).filter((p) => (only ? p.id === only : true)).reduce((n, p) => n + p.left.length, 0)
564
+ }
565
+
566
+ // ── the report ───────────────────────────────────────────────────────────────────────────────────
567
+
568
+ /** The plan as Markdown: the passes, then each pass's places, file by file. */
569
+ export function formatReport(result, { write = false, only = null } = {}) {
570
+ const { table, work } = result
571
+ const out = []
572
+ const major = table.sdk.to
573
+ const passes = passesOf(result, { write })
574
+ const pass = (id) => passes.find((p) => p.id === id)
575
+ const show = (id) => !only || only === id
576
+ const where = (w) => `\`${w.file}:${w.line}\``
577
+ const of = (kind) => work.filter((w) => w.kind === kind)
578
+
579
+ out.push(`# Moving to SDK ${major}`, '')
580
+
581
+ if (!only) {
582
+ out.push('## The passes', '',
583
+ 'Do them in this order, one at a time. A pass is finished when its check passes, not before:',
584
+ 'run `npx smartlinks-upgrade --check <pass>` (it exits 0 when nothing is left), or the type-check where it says so.', '',
585
+ '| | Pass | Left | Finished when |', '|---|---|---|---|')
586
+ const done = { script: 'nothing is left here', 'type-check': 'the app type-checks, and nothing is left here' }
587
+ passes.forEach((p, i) => {
588
+ const gone = p.id === 'lists' ? p.left.filter((w) => w.passes.length).length : 0
589
+ const hidden = p.id === 'lists' ? p.left.filter((w) => w.untyped).length : 0
590
+ const left = p.id === 'lists' ? `${plural(p.all.length, 'call')} to go through${gone ? `, ${gone} passing an option that is gone` : ''}${hidden ? `, ${hidden} the type-check can't see` : ''}`
591
+ : p.id === 'pages' ? `${p.left.length} to decide${p.decided.length ? `, ${p.decided.length} decided` : ''}`
592
+ : p.id === 'automatic' ? (write ? 'done' : plural(p.total, 'edit')) : String(p.left.length)
593
+ out.push(`| ${i + 1} | **${p.title}** (\`${p.id}\`) | ${left} | ${done[p.judge]} |`)
594
+ })
595
+ out.push('', 'Then build, run the SDK doctor and the app\'s own tests, and say which screens changed. Never release: the owner does.', '')
596
+ }
597
+
598
+ const hold = of('hold')
599
+ if (hold.length && !only) {
600
+ out.push('## Leave these as they are', '', hold[0].note, '')
601
+ for (const w of hold) out.push(`- ${where(w)} \`${w.name}\``)
602
+ out.push('')
603
+ }
604
+
605
+ const bad = result.packages.filter((p) => !p.ok)
606
+ if (bad.length && !only) {
607
+ out.push('## Packages to update first', '')
608
+ for (const p of bad) out.push(`- \`${p.name}\` ${p.version} is built for SDK \`${p.range}\`. Install a version built for SDK ${major}, or it will read the old shapes.`)
609
+ out.push('')
610
+ }
611
+
612
+ if (show('automatic')) {
613
+ const p = pass('automatic')
614
+ const manifestChange = result.manifest && result.manifest.from !== result.manifest.to
615
+ out.push(`## 1. ${p.title}`, '', write ? 'Made by the script:' : p.how, '')
616
+ if (!p.total) out.push('Nothing mechanical to change.', '')
617
+ for (const f of result.files) out.push(`- \`${f.file}\`: ${plural(f.edits, 'edit')} (renamed calls, dropped arguments, imports)`)
618
+ if (manifestChange) out.push(`- \`${result.manifest.file}\`: \`sharedDependencies\` ${result.manifest.from} → ${result.manifest.to}`)
619
+ if (p.total) out.push('')
620
+ }
621
+
622
+ if (show('replace')) {
623
+ const p = pass('replace')
624
+ out.push(`## 2. ${p.title} (${p.left.length} left)`, '')
625
+ if (!p.left.length) out.push('Nothing left.', '')
626
+ else {
627
+ out.push(p.how, '')
628
+ for (const w of [...of('removed'), ...of('by-hand')]) out.push(`- ${where(w)} \`${w.name}\`${w.to ? ` → \`${w.to}\`` : ''}. ${w.note}`)
629
+ for (const w of [...of('option'), ...of('option-check')]) out.push(`- ${where(w)} \`${w.name}\` ${w.kind === 'option' ? 'passes' : 'may pass'} \`${w.option}\`. ${w.note}`)
630
+ out.push('')
631
+ }
632
+ }
633
+
634
+ if (show('lists')) {
635
+ const p = pass('lists')
636
+ out.push(`## 3. ${p.title} (${plural(p.all.length, 'call')})`, '')
637
+ if (!p.all.length) out.push('This app calls no list that changed.', '')
638
+ else {
639
+ out.push('Each of these now returns `{ items, nextCursor, count? }`. At each place: read the list from `.items`,',
640
+ 'a total from `.count`, "is there more" from `.nextCursor !== null`, and page with `cursor`, not `offset` or `page`.',
641
+ 'Search is `q`, sorting is `orderBy: [{ field: \'asc\' | \'desc\' }]`, a date field takes `{ gte, lte }`, related things are `expand`.', '',
642
+ '**Finished when the app type-checks** (`npx tsc --noEmit`), no call below still passes an option that is gone,',
643
+ 'and none is marked **typed `any`**. A call reached through `any` (`(SL as any).batch.list(…)`, `const res: any = await …`)',
644
+ 'compiles whatever it does with the answer, so the type-check passes without having looked at it. Take the `any` away',
645
+ '(best: the type-check then does the work), or go through the call and put `// sl-upgrade: ok <why>` on the line above.',
646
+ 'In a JavaScript app there is no type-check to lean on: go through every call below.', '')
647
+ const byFile = new Map()
648
+ for (const w of p.all) byFile.set(w.file, [...(byFile.get(w.file) || []), w])
649
+ for (const [file, items] of byFile) {
650
+ out.push(`### \`${file}\``, '')
651
+ for (const w of items) {
652
+ const bits = [`was \`${w.before}\``]
653
+ if (w.passes.length) bits.push(`**passes ${w.passes.map((o) => '`' + o + '`').join(', ')}**, which is gone`)
654
+ if (w.untyped) bits.push('**typed `any`**: the type-check can\'t see this call')
655
+ if (w.firstPageOnly) bits.push('**used to return everything**, now one page (pass 4)')
656
+ if (!w.paged) bits.push('always returned whole (no `limit` or `cursor`)')
657
+ if (!w.called) bits.push('passed as a value, not called here: follow it to where the result is read')
658
+ if (w.note) bits.push(w.note)
659
+ out.push(`- line ${w.line} \`${w.name}\`: ${bits.join('; ')}`)
660
+ }
661
+ out.push('')
662
+ }
663
+ }
664
+ }
665
+
666
+ if (show('pages')) {
667
+ const p = pass('pages')
668
+ out.push(`## 4. ${p.title} (${p.left.length} to decide${p.decided.length ? `, ${p.decided.length} decided` : ''})`, '')
669
+ if (!p.left.length && !p.decided.length) out.push('This app calls no list that used to return everything.', '')
670
+ else {
671
+ out.push(p.how, '',
672
+ 'This is the change that breaks an app quietly: code that reads `.items` compiles and runs, and is wrong once there are more than 50.', '')
673
+ for (const w of p.left) out.push(`- ${where(w)} \`${w.name}\`${w.called ? '' : ' (passed as a value, not called here)'}`)
674
+ if (p.left.length) out.push('')
675
+ if (p.decided.length) {
676
+ out.push('Decided:', '')
677
+ for (const w of p.decided) out.push(`- ${where(w)} \`${w.name}\`: ${w.decided}`)
678
+ out.push('')
679
+ }
680
+ }
681
+ }
682
+
683
+ if (show('errors')) {
684
+ const p = pass('errors')
685
+ out.push(`## 5. ${p.title} (${p.left.length} left)`, '')
686
+ if (!p.left.length) out.push('Nothing left.', '')
687
+ else { out.push(p.how, ''); for (const w of p.left) out.push(`- ${where(w)} ${w.note}`); out.push('') }
688
+ }
689
+
690
+ if (!only) {
691
+ out.push('## What no script can see', '')
692
+ for (const b of result.behaviour) out.push(`- **${b.name}.** ${b.note}`)
693
+ for (const f of result.fields) out.push(`- **\`${f.name}\`** (a field).${f.to ? ` Use \`${f.to}\`.` : ''} ${f.note}`)
694
+ out.push('', `Everything above is explained in \`docs/${path.basename(table.guide)}\` in this package.`, '')
695
+ }
696
+ return out.join('\n')
697
+ }
698
+
699
+ /** One line for a log. */
700
+ export function summary(result, { write = false } = {}) {
701
+ const n = (k) => result.work.filter((w) => w.kind === k).length
702
+ const passes = passesOf(result, { write })
703
+ const left = (id) => passes.find((p) => p.id === id).left.length
704
+ return `${plural(result.files.reduce((a, f) => a + f.edits, 0), 'mechanical edit')} in ${plural(result.files.length, 'file')}; `
705
+ + `left to do: ${plural(left('replace'), 'call or option', 'calls or options')} to replace, ${plural(n('list'), 'list call')} to go through, `
706
+ + `${plural(left('pages'), 'list')} to decide (one page or all), ${plural(left('errors'), 'check')}`
707
+ + (n('hold') ? `; ${plural(n('hold'), 'call')} to leave alone` : '')
708
+ }