@teleporthq/teleport-plugin-common 0.45.3-alpha.0 → 0.45.13

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 (200) hide show
  1. package/__tests__/builders/html-builders.ts +9 -2
  2. package/__tests__/builders/style-builders.ts +135 -1
  3. package/__tests__/node-handlers/node-to-html/index.ts +2 -0
  4. package/__tests__/node-handlers/node-to-jsx/attribute-value-mapper.ts +77 -0
  5. package/__tests__/node-handlers/node-to-jsx/calendar-events-reviver.ts +176 -0
  6. package/__tests__/node-handlers/node-to-jsx/chart-data-guard.ts +101 -0
  7. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-ecommerce-source.ts +79 -0
  8. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-loading.ts +122 -0
  9. package/__tests__/node-handlers/node-to-jsx/index.ts +719 -3
  10. package/__tests__/node-handlers/node-to-jsx/url-search-params-expression.ts +59 -0
  11. package/__tests__/node-handlers/node-to-jsx/utils.ts +635 -3
  12. package/__tests__/utils/ast-utils.ts +188 -0
  13. package/__tests__/utils/content-property-sanitiser.ts +156 -0
  14. package/__tests__/utils/page-seeds-state-from-data-source.ts +70 -0
  15. package/__tests__/utils/parse-string-with-template-expressions.ts +82 -0
  16. package/__tests__/utils/resource-auth-scheme.ts +55 -0
  17. package/__tests__/utils/route-utils.ts +118 -0
  18. package/__tests__/utils/style-utils.ts +59 -0
  19. package/__tests__/utils/template-expression-balance.ts +83 -0
  20. package/__tests__/utils/url-query-writer.ts +239 -0
  21. package/__tests__/utils/url-search-param-sync.ts +138 -0
  22. package/__tests__/utils/url-search-params.ts +48 -0
  23. package/dist/cjs/builders/ast-builders.d.ts +2 -0
  24. package/dist/cjs/builders/ast-builders.d.ts.map +1 -1
  25. package/dist/cjs/builders/ast-builders.js +41 -3
  26. package/dist/cjs/builders/ast-builders.js.map +1 -1
  27. package/dist/cjs/builders/hast-builders.d.ts +1 -0
  28. package/dist/cjs/builders/hast-builders.d.ts.map +1 -1
  29. package/dist/cjs/builders/hast-builders.js +11 -1
  30. package/dist/cjs/builders/hast-builders.js.map +1 -1
  31. package/dist/cjs/builders/style-builders.d.ts +8 -2
  32. package/dist/cjs/builders/style-builders.d.ts.map +1 -1
  33. package/dist/cjs/builders/style-builders.js +80 -33
  34. package/dist/cjs/builders/style-builders.js.map +1 -1
  35. package/dist/cjs/index.d.ts +5 -1
  36. package/dist/cjs/index.d.ts.map +1 -1
  37. package/dist/cjs/index.js +10 -1
  38. package/dist/cjs/index.js.map +1 -1
  39. package/dist/cjs/node-handlers/node-to-html/constants.d.ts.map +1 -1
  40. package/dist/cjs/node-handlers/node-to-html/constants.js +2 -0
  41. package/dist/cjs/node-handlers/node-to-html/constants.js.map +1 -1
  42. package/dist/cjs/node-handlers/node-to-html/index.d.ts.map +1 -1
  43. package/dist/cjs/node-handlers/node-to-html/index.js +69 -1
  44. package/dist/cjs/node-handlers/node-to-html/index.js.map +1 -1
  45. package/dist/cjs/node-handlers/node-to-html/types.d.ts +5 -1
  46. package/dist/cjs/node-handlers/node-to-html/types.d.ts.map +1 -1
  47. package/dist/cjs/node-handlers/node-to-html/utils.d.ts +2 -1
  48. package/dist/cjs/node-handlers/node-to-html/utils.d.ts.map +1 -1
  49. package/dist/cjs/node-handlers/node-to-html/utils.js +174 -13
  50. package/dist/cjs/node-handlers/node-to-html/utils.js.map +1 -1
  51. package/dist/cjs/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  52. package/dist/cjs/node-handlers/node-to-jsx/index.js +1443 -45
  53. package/dist/cjs/node-handlers/node-to-jsx/index.js.map +1 -1
  54. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts +60 -6
  55. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  56. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts +80 -7
  57. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  58. package/dist/cjs/node-handlers/node-to-jsx/utils.js +883 -72
  59. package/dist/cjs/node-handlers/node-to-jsx/utils.js.map +1 -1
  60. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  61. package/dist/cjs/utils/ast-utils.d.ts +163 -11
  62. package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
  63. package/dist/cjs/utils/ast-utils.js +1013 -75
  64. package/dist/cjs/utils/ast-utils.js.map +1 -1
  65. package/dist/cjs/utils/hast-utils.d.ts +8 -6
  66. package/dist/cjs/utils/hast-utils.d.ts.map +1 -1
  67. package/dist/cjs/utils/hast-utils.js +28 -4
  68. package/dist/cjs/utils/hast-utils.js.map +1 -1
  69. package/dist/cjs/utils/nested-selector-commas.d.ts +2 -0
  70. package/dist/cjs/utils/nested-selector-commas.d.ts.map +1 -0
  71. package/dist/cjs/utils/nested-selector-commas.js +81 -0
  72. package/dist/cjs/utils/nested-selector-commas.js.map +1 -0
  73. package/dist/cjs/utils/route-utils.d.ts +117 -0
  74. package/dist/cjs/utils/route-utils.d.ts.map +1 -0
  75. package/dist/cjs/utils/route-utils.js +212 -0
  76. package/dist/cjs/utils/route-utils.js.map +1 -0
  77. package/dist/cjs/utils/style-utils.d.ts +1 -0
  78. package/dist/cjs/utils/style-utils.d.ts.map +1 -1
  79. package/dist/cjs/utils/style-utils.js +181 -2
  80. package/dist/cjs/utils/style-utils.js.map +1 -1
  81. package/dist/cjs/utils/template-expression-balance.d.ts +58 -0
  82. package/dist/cjs/utils/template-expression-balance.d.ts.map +1 -0
  83. package/dist/cjs/utils/template-expression-balance.js +181 -0
  84. package/dist/cjs/utils/template-expression-balance.js.map +1 -0
  85. package/dist/cjs/utils/types.d.ts +3 -0
  86. package/dist/cjs/utils/types.d.ts.map +1 -0
  87. package/dist/cjs/utils/types.js +3 -0
  88. package/dist/cjs/utils/types.js.map +1 -0
  89. package/dist/cjs/utils/url-query-writer.d.ts +123 -0
  90. package/dist/cjs/utils/url-query-writer.d.ts.map +1 -0
  91. package/dist/cjs/utils/url-query-writer.js +260 -0
  92. package/dist/cjs/utils/url-query-writer.js.map +1 -0
  93. package/dist/cjs/utils/url-search-param-sync.d.ts +4 -0
  94. package/dist/cjs/utils/url-search-param-sync.d.ts.map +1 -0
  95. package/dist/cjs/utils/url-search-param-sync.js +241 -0
  96. package/dist/cjs/utils/url-search-param-sync.js.map +1 -0
  97. package/dist/cjs/utils/url-search-params.d.ts +48 -0
  98. package/dist/cjs/utils/url-search-params.d.ts.map +1 -0
  99. package/dist/cjs/utils/url-search-params.js +109 -0
  100. package/dist/cjs/utils/url-search-params.js.map +1 -0
  101. package/dist/esm/builders/ast-builders.d.ts +2 -0
  102. package/dist/esm/builders/ast-builders.d.ts.map +1 -1
  103. package/dist/esm/builders/ast-builders.js +40 -4
  104. package/dist/esm/builders/ast-builders.js.map +1 -1
  105. package/dist/esm/builders/hast-builders.d.ts +1 -0
  106. package/dist/esm/builders/hast-builders.d.ts.map +1 -1
  107. package/dist/esm/builders/hast-builders.js +9 -0
  108. package/dist/esm/builders/hast-builders.js.map +1 -1
  109. package/dist/esm/builders/style-builders.d.ts +8 -2
  110. package/dist/esm/builders/style-builders.d.ts.map +1 -1
  111. package/dist/esm/builders/style-builders.js +78 -32
  112. package/dist/esm/builders/style-builders.js.map +1 -1
  113. package/dist/esm/index.d.ts +5 -1
  114. package/dist/esm/index.d.ts.map +1 -1
  115. package/dist/esm/index.js +5 -1
  116. package/dist/esm/index.js.map +1 -1
  117. package/dist/esm/node-handlers/node-to-html/constants.d.ts.map +1 -1
  118. package/dist/esm/node-handlers/node-to-html/constants.js +2 -0
  119. package/dist/esm/node-handlers/node-to-html/constants.js.map +1 -1
  120. package/dist/esm/node-handlers/node-to-html/index.d.ts.map +1 -1
  121. package/dist/esm/node-handlers/node-to-html/index.js +71 -3
  122. package/dist/esm/node-handlers/node-to-html/index.js.map +1 -1
  123. package/dist/esm/node-handlers/node-to-html/types.d.ts +5 -1
  124. package/dist/esm/node-handlers/node-to-html/types.d.ts.map +1 -1
  125. package/dist/esm/node-handlers/node-to-html/utils.d.ts +2 -1
  126. package/dist/esm/node-handlers/node-to-html/utils.d.ts.map +1 -1
  127. package/dist/esm/node-handlers/node-to-html/utils.js +170 -13
  128. package/dist/esm/node-handlers/node-to-html/utils.js.map +1 -1
  129. package/dist/esm/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  130. package/dist/esm/node-handlers/node-to-jsx/index.js +1442 -47
  131. package/dist/esm/node-handlers/node-to-jsx/index.js.map +1 -1
  132. package/dist/esm/node-handlers/node-to-jsx/types.d.ts +60 -6
  133. package/dist/esm/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  134. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts +80 -7
  135. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  136. package/dist/esm/node-handlers/node-to-jsx/utils.js +875 -70
  137. package/dist/esm/node-handlers/node-to-jsx/utils.js.map +1 -1
  138. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  139. package/dist/esm/utils/ast-utils.d.ts +163 -11
  140. package/dist/esm/utils/ast-utils.d.ts.map +1 -1
  141. package/dist/esm/utils/ast-utils.js +989 -75
  142. package/dist/esm/utils/ast-utils.js.map +1 -1
  143. package/dist/esm/utils/hast-utils.d.ts +8 -6
  144. package/dist/esm/utils/hast-utils.d.ts.map +1 -1
  145. package/dist/esm/utils/hast-utils.js +26 -3
  146. package/dist/esm/utils/hast-utils.js.map +1 -1
  147. package/dist/esm/utils/nested-selector-commas.d.ts +2 -0
  148. package/dist/esm/utils/nested-selector-commas.d.ts.map +1 -0
  149. package/dist/esm/utils/nested-selector-commas.js +77 -0
  150. package/dist/esm/utils/nested-selector-commas.js.map +1 -0
  151. package/dist/esm/utils/route-utils.d.ts +117 -0
  152. package/dist/esm/utils/route-utils.d.ts.map +1 -0
  153. package/dist/esm/utils/route-utils.js +179 -0
  154. package/dist/esm/utils/route-utils.js.map +1 -0
  155. package/dist/esm/utils/style-utils.d.ts +1 -0
  156. package/dist/esm/utils/style-utils.d.ts.map +1 -1
  157. package/dist/esm/utils/style-utils.js +179 -1
  158. package/dist/esm/utils/style-utils.js.map +1 -1
  159. package/dist/esm/utils/template-expression-balance.d.ts +58 -0
  160. package/dist/esm/utils/template-expression-balance.d.ts.map +1 -0
  161. package/dist/esm/utils/template-expression-balance.js +174 -0
  162. package/dist/esm/utils/template-expression-balance.js.map +1 -0
  163. package/dist/esm/utils/types.d.ts +3 -0
  164. package/dist/esm/utils/types.d.ts.map +1 -0
  165. package/dist/esm/utils/types.js +2 -0
  166. package/dist/esm/utils/types.js.map +1 -0
  167. package/dist/esm/utils/url-query-writer.d.ts +123 -0
  168. package/dist/esm/utils/url-query-writer.d.ts.map +1 -0
  169. package/dist/esm/utils/url-query-writer.js +229 -0
  170. package/dist/esm/utils/url-query-writer.js.map +1 -0
  171. package/dist/esm/utils/url-search-param-sync.d.ts +4 -0
  172. package/dist/esm/utils/url-search-param-sync.d.ts.map +1 -0
  173. package/dist/esm/utils/url-search-param-sync.js +213 -0
  174. package/dist/esm/utils/url-search-param-sync.js.map +1 -0
  175. package/dist/esm/utils/url-search-params.d.ts +48 -0
  176. package/dist/esm/utils/url-search-params.d.ts.map +1 -0
  177. package/dist/esm/utils/url-search-params.js +81 -0
  178. package/dist/esm/utils/url-search-params.js.map +1 -0
  179. package/package.json +4 -4
  180. package/src/builders/ast-builders.ts +80 -3
  181. package/src/builders/hast-builders.ts +11 -0
  182. package/src/builders/style-builders.ts +121 -43
  183. package/src/index.ts +22 -1
  184. package/src/node-handlers/node-to-html/constants.ts +2 -0
  185. package/src/node-handlers/node-to-html/index.ts +126 -6
  186. package/src/node-handlers/node-to-html/types.ts +6 -0
  187. package/src/node-handlers/node-to-html/utils.ts +228 -14
  188. package/src/node-handlers/node-to-jsx/index.ts +2135 -62
  189. package/src/node-handlers/node-to-jsx/types.ts +75 -32
  190. package/src/node-handlers/node-to-jsx/utils.ts +1173 -84
  191. package/src/utils/ast-utils.ts +1316 -127
  192. package/src/utils/hast-utils.ts +37 -9
  193. package/src/utils/nested-selector-commas.ts +88 -0
  194. package/src/utils/route-utils.ts +214 -0
  195. package/src/utils/style-utils.ts +183 -1
  196. package/src/utils/template-expression-balance.ts +196 -0
  197. package/src/utils/types.ts +25 -0
  198. package/src/utils/url-query-writer.ts +318 -0
  199. package/src/utils/url-search-param-sync.ts +303 -0
  200. package/src/utils/url-search-params.ts +122 -0
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Delimiter balancing for `{{ … }}` binding expressions.
3
+ *
4
+ * THE DEFECT THIS EXISTS FOR. `parseStringWithTemplateExpressions` converted a
5
+ * UIDL string into a template literal and then handed the result straight to
6
+ * Babel. When the binding inside was unbalanced the produced source did not
7
+ * parse, `parse()` threw, and — because the inline-style caller has no
8
+ * try/catch — the SyntaxError escaped all the way out and killed the ENTIRE
9
+ * project build:
10
+ *
11
+ * const x = `translateX(${-(cameraX || ''}px) }px)`
12
+ * ^ Unexpected token, expected ","
13
+ *
14
+ * Two separate faults produced that line. The interpolated expression
15
+ * `-(cameraX || ''` was missing its closing paren, and the "re-close the CSS
16
+ * function" step counted parentheses across the WHOLE string — including the
17
+ * ones inside `${…}` — decided one was missing, and appended `px)` to the end,
18
+ * which could never help because the imbalance was inside the interpolation.
19
+ *
20
+ * One bad binding in one style property must never cost a project its build.
21
+ * These helpers make the imbalance repairable where it actually is, and let the
22
+ * caller degrade a single value instead of aborting.
23
+ */
24
+
25
+ /** Closing delimiter for each opener that nests inside an expression. */
26
+ const CLOSER_FOR_OPENER: Record<string, string> = {
27
+ '(': ')',
28
+ '[': ']',
29
+ '{': '}',
30
+ }
31
+
32
+ const CLOSERS = new Set(Object.values(CLOSER_FOR_OPENER))
33
+ const QUOTES = new Set(["'", '"', '`'])
34
+
35
+ export interface ExpressionScan {
36
+ /** Openers still waiting for their closer, outermost first. */
37
+ unclosed: string[]
38
+ /** Closers that never had a matching opener. */
39
+ strayCloserCount: number
40
+ /** The quote character still open at the end of the scan, if any. */
41
+ unterminatedQuote: string | null
42
+ }
43
+
44
+ /**
45
+ * Single left-to-right pass over an expression, quote and escape aware.
46
+ * Characters inside a string literal never affect nesting.
47
+ */
48
+ export const scanExpression = (expression: string): ExpressionScan => {
49
+ const unclosed: string[] = []
50
+ let strayCloserCount = 0
51
+ let quote: string | null = null
52
+
53
+ for (let index = 0; index < expression.length; index++) {
54
+ const char = expression[index]
55
+
56
+ if (char === '\\') {
57
+ index++
58
+ continue
59
+ }
60
+
61
+ if (quote !== null) {
62
+ if (char === quote) {
63
+ quote = null
64
+ }
65
+ continue
66
+ }
67
+
68
+ if (QUOTES.has(char)) {
69
+ quote = char
70
+ continue
71
+ }
72
+
73
+ if (CLOSER_FOR_OPENER[char]) {
74
+ unclosed.push(char)
75
+ continue
76
+ }
77
+
78
+ if (CLOSERS.has(char)) {
79
+ const expected = unclosed.length > 0 ? CLOSER_FOR_OPENER[unclosed[unclosed.length - 1]] : null
80
+ if (expected === char) {
81
+ unclosed.pop()
82
+ } else {
83
+ strayCloserCount++
84
+ }
85
+ }
86
+ }
87
+
88
+ return { unclosed, strayCloserCount, unterminatedQuote: quote }
89
+ }
90
+
91
+ /** True when every quote and bracket closes and no closer is stray. */
92
+ export const isBalancedExpression = (expression: string): boolean => {
93
+ const scan = scanExpression(expression)
94
+ return (
95
+ scan.unclosed.length === 0 && scan.strayCloserCount === 0 && scan.unterminatedQuote === null
96
+ )
97
+ }
98
+
99
+ /**
100
+ * Close an expression that ends mid-quote or mid-bracket:
101
+ * `-(cameraX || ''` → `-(cameraX || '')`.
102
+ *
103
+ * Returns the expression unchanged when it is already balanced, and when the
104
+ * imbalance is a STRAY CLOSER — appending cannot fix a missing opener, and
105
+ * inventing one would be a guess.
106
+ */
107
+ export const balanceExpression = (expression: string): string => {
108
+ const scan = scanExpression(expression)
109
+ if (scan.strayCloserCount > 0) {
110
+ return expression
111
+ }
112
+ if (scan.unclosed.length === 0 && scan.unterminatedQuote === null) {
113
+ return expression
114
+ }
115
+
116
+ const suffix = [scan.unterminatedQuote || '', ...unclosedInReverse(scan.unclosed)].join('')
117
+
118
+ return expression + suffix
119
+ }
120
+
121
+ const unclosedInReverse = (unclosed: string[]): string[] =>
122
+ unclosed
123
+ .slice()
124
+ .reverse()
125
+ .map((opener) => CLOSER_FOR_OPENER[opener])
126
+
127
+ /**
128
+ * Parenthesis balance of the STATIC parts of a template string — everything
129
+ * outside `${…}`.
130
+ *
131
+ * This is the number the "re-close the CSS function" step needs. Counting over
132
+ * the whole string mixes in the expressions' own parentheses, so an imbalance
133
+ * INSIDE an interpolation reads as a missing close on the CSS function and the
134
+ * step appends a unit and a `)` that belong nowhere.
135
+ */
136
+ export const countUnclosedStaticParens = (templateStr: string): number => {
137
+ let depth = 0
138
+ let index = 0
139
+
140
+ while (index < templateStr.length) {
141
+ if (templateStr[index] === '$' && templateStr[index + 1] === '{') {
142
+ index = skipInterpolation(templateStr, index + 2)
143
+ continue
144
+ }
145
+ if (templateStr[index] === '(') {
146
+ depth++
147
+ } else if (templateStr[index] === ')') {
148
+ depth--
149
+ }
150
+ index++
151
+ }
152
+
153
+ return depth > 0 ? depth : 0
154
+ }
155
+
156
+ /**
157
+ * Index just past the `}` that closes an interpolation opened at `start`.
158
+ * Tracks nested braces and string literals so `${ {a:'}'} }` is skipped whole.
159
+ * An unterminated interpolation consumes the rest of the string.
160
+ */
161
+ const skipInterpolation = (templateStr: string, start: number): number => {
162
+ let depth = 1
163
+ let quote: string | null = null
164
+
165
+ for (let index = start; index < templateStr.length; index++) {
166
+ const char = templateStr[index]
167
+
168
+ if (char === '\\') {
169
+ index++
170
+ continue
171
+ }
172
+
173
+ if (quote !== null) {
174
+ if (char === quote) {
175
+ quote = null
176
+ }
177
+ continue
178
+ }
179
+
180
+ if (QUOTES.has(char)) {
181
+ quote = char
182
+ continue
183
+ }
184
+
185
+ if (char === '{') {
186
+ depth++
187
+ } else if (char === '}') {
188
+ depth--
189
+ if (depth === 0) {
190
+ return index + 1
191
+ }
192
+ }
193
+ }
194
+
195
+ return templateStr.length
196
+ }
@@ -0,0 +1,25 @@
1
+ export type BinaryOperator =
2
+ | '==='
3
+ | '+'
4
+ | '-'
5
+ | '/'
6
+ | '%'
7
+ | '*'
8
+ | '**'
9
+ | '&'
10
+ | '|'
11
+ | '>>'
12
+ | '>>>'
13
+ | '<<'
14
+ | '^'
15
+ | '=='
16
+ | '!='
17
+ | '!=='
18
+ | 'in'
19
+ | 'instanceof'
20
+ | '>'
21
+ | '<'
22
+ | '>='
23
+ | '<='
24
+
25
+ export type UnaryOperation = '+' | '-' | 'void' | 'throw' | 'delete' | '!' | '~' | 'typeof'
@@ -0,0 +1,318 @@
1
+ import * as types from '@babel/types'
2
+
3
+ /**
4
+ * The ONE place a generated page is allowed to write `router.query` from.
5
+ *
6
+ * ## The defect this exists to make impossible
7
+ *
8
+ * Every URL-bound control used to own a `useEffect` that did
9
+ *
10
+ * const __nextQuery = { ...router.query } // its own snapshot
11
+ * __nextQuery.categoryFilter = 'Rings'
12
+ * router.replace({ pathname, query: __nextQuery }, undefined, { shallow: true })
13
+ *
14
+ * `router.query` is a per-render SHALLOW COPY that Next rebuilds only when the
15
+ * router itself re-renders (`makePublicRouterInstance` — "makes sure query is
16
+ * not stateful"), and `router.replace` updates it asynchronously. So two
17
+ * controls writing in the same flush both spread the SAME pre-change object,
18
+ * and whichever `replace` commits last silently drops the key the other had
19
+ * just added — or resurrects one it had just deleted.
20
+ *
21
+ * That is not a rare interleaving; it is the common one. Changing a filter
22
+ * resets the page, so the filter's write-back and the page's write-back always
23
+ * fire together.
24
+ *
25
+ * ⛔ And the damage does not stop at a wrong URL. Each control also has a
26
+ * READ-BACK effect that pushes `router.query` back into React state. Once a key
27
+ * is erased, the read-back clears that control's state, the write-back
28
+ * re-asserts it, the next landing erases it again — and because each round
29
+ * reads the other side's PRE-flush value, the pair computes
30
+ * `(state, url) -> (url, state)`: a swap. A swap has no fixed point off the
31
+ * diagonal, so it never converges. The observed symptom was a products list
32
+ * that re-fetched and flickered forever after picking a category while on
33
+ * page 5.
34
+ *
35
+ * ## The fix
36
+ *
37
+ * Nobody spreads `router.query` any more. All writers go through one function
38
+ * that merges into `pending` — the last query this component ASKED for —
39
+ * falling back to `router.query` only when nothing is in flight. The second
40
+ * write of a flush therefore builds on the first's payload instead of racing
41
+ * it, no key is ever lost, and with no key lost there is nothing for a
42
+ * read-back to disagree about.
43
+ *
44
+ * `pending` is dropped once every replace it was built from has settled, so an
45
+ * external navigation (a Link, browser back/forward) is never merged into a
46
+ * stale snapshot.
47
+ *
48
+ * @see `buildUrlWriteBackEffect` in `./url-search-param-sync` and
49
+ * `buildPageUrlSyncEffect` in `teleport-plugin-next-data-source` — the two
50
+ * callers, in two different packages, which is why this lives here.
51
+ */
52
+
53
+ /** `useRef` holding `{ pending, inFlight }`. Shared by every writer in a component. */
54
+ export const QUERY_SYNC_REF_ID = '__tqQuerySyncRef'
55
+
56
+ /** The write function every URL-bound control calls. */
57
+ export const QUERY_WRITER_ID = '__tqWriteQueryParam'
58
+
59
+ const refCurrent = (): types.MemberExpression =>
60
+ types.memberExpression(types.identifier(QUERY_SYNC_REF_ID), types.identifier('current'))
61
+
62
+ const refField = (field: 'pending' | 'inFlight'): types.MemberExpression =>
63
+ types.memberExpression(refCurrent(), types.identifier(field))
64
+
65
+ /**
66
+ * `__tqQuerySyncRef.current.inFlight === 0` — "the URL is settled".
67
+ *
68
+ * The page-URL effect uses it to gate its ADOPT branch: while a replace this
69
+ * component issued is still landing, `router.query` is a value the page is on
70
+ * its way OUT of, and adopting it would undo the move that is in flight.
71
+ */
72
+ export const buildQuerySettledExpr = (): types.BinaryExpression =>
73
+ types.binaryExpression('===', refField('inFlight'), types.numericLiteral(0))
74
+
75
+ /** `__tqWriteQueryParam('<paramKey>', <valueExpr>)` — `undefined` removes the key. */
76
+ export const buildQueryWriteCall = (
77
+ paramKey: string,
78
+ valueExpr: types.Expression
79
+ ): types.ExpressionStatement =>
80
+ types.expressionStatement(
81
+ types.callExpression(types.identifier(QUERY_WRITER_ID), [
82
+ types.stringLiteral(paramKey),
83
+ valueExpr,
84
+ ])
85
+ )
86
+
87
+ /**
88
+ * True when a previous plugin already emitted the declarations.
89
+ *
90
+ * Both `createNextUrlSearchParamsPlugin` and
91
+ * `createNextArrayMapperPaginationPlugin` can be the first to need them on the
92
+ * same component, and neither knows whether the other ran.
93
+ */
94
+ export const hasQuerySyncDeclarations = (body: types.Statement[]): boolean =>
95
+ body.some(
96
+ (statement) =>
97
+ statement.type === 'VariableDeclaration' &&
98
+ statement.declarations.some(
99
+ (declarator) =>
100
+ declarator.id.type === 'Identifier' && declarator.id.name === QUERY_SYNC_REF_ID
101
+ )
102
+ )
103
+
104
+ /**
105
+ * Emitted shape:
106
+ *
107
+ * const __tqQuerySyncRef = useRef({ pending: null, inFlight: 0 })
108
+ * const __tqWriteQueryParam = (key, value) => {
109
+ * const base = __tqQuerySyncRef.current.pending || router.query
110
+ * const next = { ...base }
111
+ * if (value === undefined || value === null || value === '') { delete next[key] }
112
+ * else { next[key] = String(value) }
113
+ * if (next[key] === base[key]) return
114
+ * __tqQuerySyncRef.current.pending = next
115
+ * __tqQuerySyncRef.current.inFlight += 1
116
+ * const settle = () => {
117
+ * __tqQuerySyncRef.current.inFlight -= 1
118
+ * if (__tqQuerySyncRef.current.inFlight <= 0) {
119
+ * __tqQuerySyncRef.current.inFlight = 0
120
+ * __tqQuerySyncRef.current.pending = null
121
+ * }
122
+ * }
123
+ * Promise.resolve(
124
+ * router.replace({ pathname: router.pathname, query: next }, undefined, { shallow: true })
125
+ * ).then(settle, settle)
126
+ * }
127
+ *
128
+ * Notes on the details that are load-bearing:
129
+ *
130
+ * - `next[key] === base[key]` is the ONLY bail. Comparing against the pending
131
+ * query rather than `router.query` is what makes a re-render during an
132
+ * in-flight replace a no-op instead of a duplicate write.
133
+ * - Bracket access, so a URL key that is not a JS identifier (`foo-bar`) works
134
+ * without the callers having to care.
135
+ * - `String(value)` here rather than at each call site — a number page and a
136
+ * string category then serialise identically.
137
+ * - `Promise.resolve(...)` wraps the `replace` because a stubbed router in a
138
+ * test may return a plain value; `.then(settle, settle)` releases the pending
139
+ * query on a rejected (cancelled) navigation too, so one failed replace cannot
140
+ * freeze every later write against a stale base.
141
+ * - `shallow: true` keeps `getStaticProps` out of it: the data is driven by the
142
+ * params memo, not by the URL.
143
+ */
144
+ export const buildQuerySyncDeclarations = (): types.Statement[] => {
145
+ const key = types.identifier('key')
146
+ const value = types.identifier('value')
147
+
148
+ const nextAtKey = (): types.MemberExpression =>
149
+ types.memberExpression(types.identifier('next'), types.cloneNode(key, true), true)
150
+
151
+ const settleBody = types.blockStatement([
152
+ types.expressionStatement(
153
+ types.assignmentExpression('-=', refField('inFlight'), types.numericLiteral(1))
154
+ ),
155
+ types.ifStatement(
156
+ types.binaryExpression('<=', refField('inFlight'), types.numericLiteral(0)),
157
+ types.blockStatement([
158
+ types.expressionStatement(
159
+ types.assignmentExpression('=', refField('inFlight'), types.numericLiteral(0))
160
+ ),
161
+ types.expressionStatement(
162
+ types.assignmentExpression('=', refField('pending'), types.nullLiteral())
163
+ ),
164
+ ])
165
+ ),
166
+ ])
167
+
168
+ const writerBody = types.blockStatement([
169
+ // const base = __tqQuerySyncRef.current.pending || router.query
170
+ types.variableDeclaration('const', [
171
+ types.variableDeclarator(
172
+ types.identifier('base'),
173
+ types.logicalExpression(
174
+ '||',
175
+ refField('pending'),
176
+ types.memberExpression(types.identifier('router'), types.identifier('query'))
177
+ )
178
+ ),
179
+ ]),
180
+ // const next = { ...base }
181
+ types.variableDeclaration('const', [
182
+ types.variableDeclarator(
183
+ types.identifier('next'),
184
+ types.objectExpression([types.spreadElement(types.identifier('base'))])
185
+ ),
186
+ ]),
187
+ types.ifStatement(
188
+ types.logicalExpression(
189
+ '||',
190
+ types.logicalExpression(
191
+ '||',
192
+ types.binaryExpression(
193
+ '===',
194
+ types.cloneNode(value, true),
195
+ types.identifier('undefined')
196
+ ),
197
+ types.binaryExpression('===', types.cloneNode(value, true), types.nullLiteral())
198
+ ),
199
+ types.binaryExpression('===', types.cloneNode(value, true), types.stringLiteral(''))
200
+ ),
201
+ types.blockStatement([
202
+ types.expressionStatement(
203
+ types.unaryExpression('delete', nextAtKey()) as unknown as types.Expression
204
+ ),
205
+ ]),
206
+ types.blockStatement([
207
+ types.expressionStatement(
208
+ types.assignmentExpression(
209
+ '=',
210
+ nextAtKey(),
211
+ types.callExpression(types.identifier('String'), [types.cloneNode(value, true)])
212
+ )
213
+ ),
214
+ ])
215
+ ),
216
+ // if (next[key] === base[key]) return
217
+ types.ifStatement(
218
+ types.binaryExpression(
219
+ '===',
220
+ nextAtKey(),
221
+ types.memberExpression(types.identifier('base'), types.cloneNode(key, true), true)
222
+ ),
223
+ types.returnStatement(null)
224
+ ),
225
+ types.expressionStatement(
226
+ types.assignmentExpression('=', refField('pending'), types.identifier('next'))
227
+ ),
228
+ types.expressionStatement(
229
+ types.assignmentExpression('+=', refField('inFlight'), types.numericLiteral(1))
230
+ ),
231
+ types.variableDeclaration('const', [
232
+ types.variableDeclarator(
233
+ types.identifier('settle'),
234
+ types.arrowFunctionExpression([], settleBody)
235
+ ),
236
+ ]),
237
+ types.expressionStatement(
238
+ types.callExpression(
239
+ types.memberExpression(
240
+ types.callExpression(
241
+ types.memberExpression(types.identifier('Promise'), types.identifier('resolve')),
242
+ [
243
+ types.callExpression(
244
+ types.memberExpression(types.identifier('router'), types.identifier('replace')),
245
+ [
246
+ types.objectExpression([
247
+ types.objectProperty(
248
+ types.identifier('pathname'),
249
+ types.memberExpression(
250
+ types.identifier('router'),
251
+ types.identifier('pathname')
252
+ )
253
+ ),
254
+ types.objectProperty(types.identifier('query'), types.identifier('next')),
255
+ ]),
256
+ types.identifier('undefined'),
257
+ types.objectExpression([
258
+ types.objectProperty(types.identifier('shallow'), types.booleanLiteral(true)),
259
+ ]),
260
+ ]
261
+ ),
262
+ ]
263
+ ),
264
+ types.identifier('then')
265
+ ),
266
+ [types.identifier('settle'), types.identifier('settle')]
267
+ )
268
+ ),
269
+ ])
270
+
271
+ return [
272
+ types.variableDeclaration('const', [
273
+ types.variableDeclarator(
274
+ types.identifier(QUERY_SYNC_REF_ID),
275
+ types.callExpression(types.identifier('useRef'), [
276
+ types.objectExpression([
277
+ types.objectProperty(types.identifier('pending'), types.nullLiteral()),
278
+ types.objectProperty(types.identifier('inFlight'), types.numericLiteral(0)),
279
+ ]),
280
+ ])
281
+ ),
282
+ ]),
283
+ types.variableDeclaration('const', [
284
+ types.variableDeclarator(
285
+ types.identifier(QUERY_WRITER_ID),
286
+ types.arrowFunctionExpression([key, value], writerBody)
287
+ ),
288
+ ]),
289
+ ]
290
+ }
291
+
292
+ /**
293
+ * Inserts the declarations once, immediately after `const router = useRouter()`
294
+ * when that is already in the body (it is a plain closure over `router`, so the
295
+ * order only matters for readability — nothing reads it before an effect runs).
296
+ *
297
+ * @returns `true` when it inserted, so the caller can register the `useRef`
298
+ * import dependency only when it is actually needed.
299
+ */
300
+ export const ensureQuerySyncDeclarations = (body: types.Statement[]): boolean => {
301
+ if (hasQuerySyncDeclarations(body)) {
302
+ return false
303
+ }
304
+ const routerIndex = body.findIndex(
305
+ (statement) =>
306
+ statement.type === 'VariableDeclaration' &&
307
+ statement.declarations.some(
308
+ (declarator) =>
309
+ declarator.id.type === 'Identifier' &&
310
+ declarator.id.name === 'router' &&
311
+ declarator.init?.type === 'CallExpression' &&
312
+ declarator.init.callee.type === 'Identifier' &&
313
+ declarator.init.callee.name === 'useRouter'
314
+ )
315
+ )
316
+ body.splice(routerIndex === -1 ? 0 : routerIndex + 1, 0, ...buildQuerySyncDeclarations())
317
+ return true
318
+ }