@teleporthq/teleport-plugin-next-workflows 0.43.46 → 0.43.47

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 (103) hide show
  1. package/__tests__/auth-env-secret-preservation.test.ts +35 -0
  2. package/__tests__/auth-nextauth-url.test.ts +28 -0
  3. package/__tests__/auth-session-cost.test.ts +614 -0
  4. package/__tests__/custom-js-params-env-invariance.test.ts +134 -0
  5. package/__tests__/data-node-not-awaited.test.ts +644 -0
  6. package/__tests__/element-trigger-static-attr-replace.test.ts +99 -0
  7. package/__tests__/element-visible-trigger-scoping.test.ts +296 -0
  8. package/__tests__/payment-charge-user-handler-serialization.test.ts +7 -5
  9. package/__tests__/payment-redirect-and-order-notification.test.ts +6 -4
  10. package/__tests__/raw-sql-param-binding.test.ts +82 -0
  11. package/__tests__/reserved-word-state-binding.test.ts +112 -0
  12. package/__tests__/strip-event-handler-attrs.test.ts +59 -0
  13. package/__tests__/workflow-auth-guard.test.ts +277 -0
  14. package/dist/cjs/api-route-generator.d.ts +3 -3
  15. package/dist/cjs/api-route-generator.d.ts.map +1 -1
  16. package/dist/cjs/api-route-generator.js +136 -11
  17. package/dist/cjs/api-route-generator.js.map +1 -1
  18. package/dist/cjs/auth-generator.d.ts +67 -1
  19. package/dist/cjs/auth-generator.d.ts.map +1 -1
  20. package/dist/cjs/auth-generator.js +458 -20
  21. package/dist/cjs/auth-generator.js.map +1 -1
  22. package/dist/cjs/await-result.d.ts +31 -0
  23. package/dist/cjs/await-result.d.ts.map +1 -0
  24. package/dist/cjs/await-result.js +50 -0
  25. package/dist/cjs/await-result.js.map +1 -0
  26. package/dist/cjs/executor-generator.d.ts.map +1 -1
  27. package/dist/cjs/executor-generator.js +150 -1
  28. package/dist/cjs/executor-generator.js.map +1 -1
  29. package/dist/cjs/nodes/account/account-get-current.d.ts.map +1 -1
  30. package/dist/cjs/nodes/account/account-get-current.js +44 -11
  31. package/dist/cjs/nodes/account/account-get-current.js.map +1 -1
  32. package/dist/cjs/nodes/account/account-login.d.ts.map +1 -1
  33. package/dist/cjs/nodes/account/account-login.js +10 -1
  34. package/dist/cjs/nodes/account/account-login.js.map +1 -1
  35. package/dist/cjs/raw-sql-param-binding.d.ts.map +1 -1
  36. package/dist/cjs/raw-sql-param-binding.js +32 -0
  37. package/dist/cjs/raw-sql-param-binding.js.map +1 -1
  38. package/dist/cjs/segment-splitter.d.ts.map +1 -1
  39. package/dist/cjs/segment-splitter.js +15 -7
  40. package/dist/cjs/segment-splitter.js.map +1 -1
  41. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  42. package/dist/cjs/workflow-auth-generator.d.ts +26 -0
  43. package/dist/cjs/workflow-auth-generator.d.ts.map +1 -0
  44. package/dist/cjs/workflow-auth-generator.js +166 -0
  45. package/dist/cjs/workflow-auth-generator.js.map +1 -0
  46. package/dist/cjs/workflow-component-plugin.d.ts.map +1 -1
  47. package/dist/cjs/workflow-component-plugin.js +107 -16
  48. package/dist/cjs/workflow-component-plugin.js.map +1 -1
  49. package/dist/cjs/workflow-project-plugin.d.ts +2 -1
  50. package/dist/cjs/workflow-project-plugin.d.ts.map +1 -1
  51. package/dist/cjs/workflow-project-plugin.js +170 -20
  52. package/dist/cjs/workflow-project-plugin.js.map +1 -1
  53. package/dist/esm/api-route-generator.d.ts +3 -3
  54. package/dist/esm/api-route-generator.d.ts.map +1 -1
  55. package/dist/esm/api-route-generator.js +136 -11
  56. package/dist/esm/api-route-generator.js.map +1 -1
  57. package/dist/esm/auth-generator.d.ts +67 -1
  58. package/dist/esm/auth-generator.d.ts.map +1 -1
  59. package/dist/esm/auth-generator.js +453 -19
  60. package/dist/esm/auth-generator.js.map +1 -1
  61. package/dist/esm/await-result.d.ts +31 -0
  62. package/dist/esm/await-result.d.ts.map +1 -0
  63. package/dist/esm/await-result.js +45 -0
  64. package/dist/esm/await-result.js.map +1 -0
  65. package/dist/esm/executor-generator.d.ts.map +1 -1
  66. package/dist/esm/executor-generator.js +150 -1
  67. package/dist/esm/executor-generator.js.map +1 -1
  68. package/dist/esm/nodes/account/account-get-current.d.ts.map +1 -1
  69. package/dist/esm/nodes/account/account-get-current.js +44 -11
  70. package/dist/esm/nodes/account/account-get-current.js.map +1 -1
  71. package/dist/esm/nodes/account/account-login.d.ts.map +1 -1
  72. package/dist/esm/nodes/account/account-login.js +10 -1
  73. package/dist/esm/nodes/account/account-login.js.map +1 -1
  74. package/dist/esm/raw-sql-param-binding.d.ts.map +1 -1
  75. package/dist/esm/raw-sql-param-binding.js +32 -0
  76. package/dist/esm/raw-sql-param-binding.js.map +1 -1
  77. package/dist/esm/segment-splitter.d.ts.map +1 -1
  78. package/dist/esm/segment-splitter.js +15 -7
  79. package/dist/esm/segment-splitter.js.map +1 -1
  80. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  81. package/dist/esm/workflow-auth-generator.d.ts +26 -0
  82. package/dist/esm/workflow-auth-generator.d.ts.map +1 -0
  83. package/dist/esm/workflow-auth-generator.js +161 -0
  84. package/dist/esm/workflow-auth-generator.js.map +1 -0
  85. package/dist/esm/workflow-component-plugin.d.ts.map +1 -1
  86. package/dist/esm/workflow-component-plugin.js +108 -17
  87. package/dist/esm/workflow-component-plugin.js.map +1 -1
  88. package/dist/esm/workflow-project-plugin.d.ts +2 -1
  89. package/dist/esm/workflow-project-plugin.d.ts.map +1 -1
  90. package/dist/esm/workflow-project-plugin.js +169 -20
  91. package/dist/esm/workflow-project-plugin.js.map +1 -1
  92. package/package.json +4 -4
  93. package/src/api-route-generator.ts +139 -11
  94. package/src/auth-generator.ts +471 -19
  95. package/src/await-result.ts +52 -0
  96. package/src/executor-generator.ts +150 -1
  97. package/src/nodes/account/account-get-current.ts +44 -9
  98. package/src/nodes/account/account-login.ts +12 -1
  99. package/src/raw-sql-param-binding.ts +33 -0
  100. package/src/segment-splitter.ts +15 -7
  101. package/src/workflow-auth-generator.ts +187 -0
  102. package/src/workflow-component-plugin.ts +129 -20
  103. package/src/workflow-project-plugin.ts +186 -19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-auth-generator.d.ts","sourceRoot":"","sources":["../../src/workflow-auth-generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAA;AAEnE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,8BAA8B,QAAO,MA2HjD,CAAA;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IAEpC,WAAW,EAAE,MAAM,CAAA;IAEnB,WAAW,EAAE,MAAM,CAAA;IAGnB,SAAS,EAAE,MAAM,CAAA;CAClB;AAID,eAAO,MAAM,0BAA0B,eACzB,sBAAsB,GAAG,SAAS,KAC7C,qBA4BF,CAAA"}
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The shared, stateless auth guard for generated workflow API routes, emitted
3
+ * once at `utils/workflows/workflow-auth.js`.
4
+ *
5
+ * The policy is baked into each route at build time (from the workflow's page
6
+ * protection + a scan of its graph for user-owned writes), so enforcement is a
7
+ * single local JWT decode — `getToken` reads the session cookie the browser
8
+ * already sends and verifies it with `NEXTAUTH_SECRET`. No DB, no network, no
9
+ * round trip. `next-auth/jwt` is required LAZILY so a project generated without
10
+ * authentication (where the package is absent) never fails to load this file —
11
+ * such projects also carry no protected workflows, so the guard no-ops.
12
+ */
13
+ export const generateWorkflowAuthHelperFile = () => {
14
+ return `'use strict';
15
+
16
+ // GENERATED — see generateWorkflowAuthHelperFile in
17
+ // @teleporthq/teleport-plugin-next-workflows/src/workflow-auth-generator.ts.
18
+ //
19
+ // Stateless auth guard for workflow API routes. Each route bakes its own policy
20
+ // (const __WF_AUTH) computed by the GUI mapper from the protection of the
21
+ // page(s) that trigger the workflow plus a graph scan for user-owned writes.
22
+
23
+ function getSessionToken(req) {
24
+ var secret = process.env.NEXTAUTH_SECRET;
25
+ if (!secret) {
26
+ return Promise.resolve(null);
27
+ }
28
+ var getToken;
29
+ try {
30
+ getToken = require('next-auth/jwt').getToken;
31
+ } catch (e) {
32
+ return Promise.resolve(null);
33
+ }
34
+ if (typeof getToken !== 'function') {
35
+ return Promise.resolve(null);
36
+ }
37
+ // Local cookie decode — no DB, no network.
38
+ return Promise.resolve()
39
+ .then(function () { return getToken({ req: req, secret: secret }); })
40
+ .catch(function () { return null; });
41
+ }
42
+
43
+ function sessionUserId(token) {
44
+ if (!token || typeof token !== 'object') {
45
+ return null;
46
+ }
47
+ return token.id != null ? token.id : (token.sub != null ? token.sub : null);
48
+ }
49
+
50
+ function roleOf(token) {
51
+ if (!token || typeof token !== 'object') {
52
+ return null;
53
+ }
54
+ if (typeof token.role === 'string') {
55
+ return token.role;
56
+ }
57
+ if (typeof token.roleName === 'string') {
58
+ return token.roleName;
59
+ }
60
+ if (Array.isArray(token.roles) && token.roles.length > 0 && typeof token.roles[0] === 'string') {
61
+ return token.roles[0];
62
+ }
63
+ return null;
64
+ }
65
+
66
+ // Overwrites context[nodeId] drilled down \`path\` with the session user id.
67
+ function bindPath(root, path, value) {
68
+ if (!root || !path || path.length === 0) {
69
+ return;
70
+ }
71
+ var obj = root;
72
+ for (var i = 0; i < path.length - 1; i++) {
73
+ var key = path[i];
74
+ if (obj[key] == null || typeof obj[key] !== 'object') {
75
+ obj[key] = {};
76
+ }
77
+ obj = obj[key];
78
+ }
79
+ obj[path[path.length - 1]] = value;
80
+ }
81
+
82
+ // Returns null when the request may proceed, or { status, message } to reject.
83
+ // Mutates \`context\` in place to bind user-owned columns to the session user.
84
+ async function guardWorkflowRequest(req, context, policy) {
85
+ if (!policy) {
86
+ return null;
87
+ }
88
+
89
+ // Trusted internal server-to-server calls (e.g. password reset, server jobs)
90
+ // present the app secret in a header; only server code can read
91
+ // NEXTAUTH_SECRET, so a browser cannot forge it. These bypass the check.
92
+ var internal = req && req.headers && req.headers['x-internal-data-secret'];
93
+ if (internal && process.env.NEXTAUTH_SECRET && internal === process.env.NEXTAUTH_SECRET) {
94
+ return null;
95
+ }
96
+
97
+ var token = await getSessionToken(req);
98
+
99
+ if (policy.requiresAuth && !token) {
100
+ return { status: 401, message: 'Unauthenticated' };
101
+ }
102
+
103
+ var roles = policy.allowedRoles || [];
104
+ if (policy.requiresAuth && roles.length > 0) {
105
+ var role = roleOf(token);
106
+ if (!role || roles.indexOf(role) < 0) {
107
+ return { status: 403, message: 'Forbidden' };
108
+ }
109
+ }
110
+
111
+ // Identity binding: force every user-owned column to the AUTHENTICATED session
112
+ // id so a caller can never act on another user's rows. Only when a session is
113
+ // present — a guest keeps their (anonymous) client identity, which is why a
114
+ // guest-capable public write is not blocked here.
115
+ if (policy.userScoped && context) {
116
+ var sid = sessionUserId(token);
117
+ if (sid != null) {
118
+ var bindings = (policy.userScoped && policy.userScoped.bindings) || [];
119
+ for (var i = 0; i < bindings.length; i++) {
120
+ var b = bindings[i];
121
+ if (b && b.nodeId) {
122
+ if (context[b.nodeId] == null || typeof context[b.nodeId] !== 'object') {
123
+ context[b.nodeId] = {};
124
+ }
125
+ bindPath(context[b.nodeId], b.path || [], sid);
126
+ }
127
+ }
128
+ }
129
+ }
130
+
131
+ return null;
132
+ }
133
+
134
+ module.exports = { guardWorkflowRequest: guardWorkflowRequest };
135
+ `;
136
+ };
137
+ const EMPTY_INJECTION = { requireLine: '', policyConst: '', guardCall: '' };
138
+ export const buildWorkflowAuthInjection = (protection) => {
139
+ if (!protection || (!protection.requiresAuth && !protection.userScoped)) {
140
+ return EMPTY_INJECTION;
141
+ }
142
+ // Only the fields the runtime guard reads — `derivedFrom` is build-time only.
143
+ const policy = {
144
+ requiresAuth: !!protection.requiresAuth,
145
+ allowedRoles: protection.allowedRoles || [],
146
+ };
147
+ if (protection.userScoped) {
148
+ policy.userScoped = protection.userScoped;
149
+ }
150
+ return {
151
+ requireLine: `const __wfAuth = require('../../../utils/workflows/workflow-auth');\n`,
152
+ policyConst: `const __WF_AUTH = ${JSON.stringify(policy)};\n`,
153
+ guardCall: `
154
+ const __authError = await __wfAuth.guardWorkflowRequest(req, context, __WF_AUTH);
155
+ if (__authError) {
156
+ res.status(__authError.status).json({ error: __authError.message });
157
+ return;
158
+ }`,
159
+ };
160
+ };
161
+ //# sourceMappingURL=workflow-auth-generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-auth-generator.js","sourceRoot":"","sources":["../../src/workflow-auth-generator.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAW,EAAE;IACzD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyHR,CAAA;AACD,CAAC,CAAA;AAiBD,MAAM,eAAe,GAA0B,EAAE,WAAW,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAA;AAElG,MAAM,CAAC,MAAM,0BAA0B,GAAG,CACxC,UAA8C,EACvB,EAAE;IACzB,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,UAAU,CAAC,YAAY,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE;QACvE,OAAO,eAAe,CAAA;KACvB;IAED,8EAA8E;IAC9E,MAAM,MAAM,GAIR;QACF,YAAY,EAAE,CAAC,CAAC,UAAU,CAAC,YAAY;QACvC,YAAY,EAAE,UAAU,CAAC,YAAY,IAAI,EAAE;KAC5C,CAAA;IACD,IAAI,UAAU,CAAC,UAAU,EAAE;QACzB,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC,UAAU,CAAA;KAC1C;IAED,OAAO;QACL,WAAW,EAAE,uEAAuE;QACpF,WAAW,EAAE,qBAAqB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK;QAC7D,SAAS,EAAE;;;;;MAKT;KACH,CAAA;AACH,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-component-plugin.d.ts","sourceRoot":"","sources":["../../src/workflow-component-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,sBAAsB,EAUvB,MAAM,4BAA4B,CAAA;AAcnC,UAAU,oBAAoB;IAC5B,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AA8JD,eAAO,MAAM,wBAAwB,EAAE,sBAAsB,CAAC,oBAAoB,CAycjF,CAAA"}
1
+ {"version":3,"file":"workflow-component-plugin.d.ts","sourceRoot":"","sources":["../../src/workflow-component-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,sBAAsB,EAUvB,MAAM,4BAA4B,CAAA;AAenC,UAAU,oBAAoB;IAC5B,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAiLD,eAAO,MAAM,wBAAwB,EAAE,sBAAsB,CAAC,oBAAoB,CAoejF,CAAA"}
@@ -1,7 +1,8 @@
1
1
  import { ChunkType, FileType, } from '@teleporthq/teleport-types';
2
2
  import * as types from '@babel/types';
3
- import { StringUtils } from '@teleporthq/teleport-shared';
3
+ import { JSIdentifiers, StringUtils } from '@teleporthq/teleport-shared';
4
4
  import { splitIntoSegments, resolveNodeExecutionEnv, redactServerNodeConfig, } from './segment-splitter';
5
+ import { isFireAndForgetSegment } from './await-result';
5
6
  import { getAPIRouteFileName, hasStreamingAINode } from './api-route-generator';
6
7
  import { REALTIME_TRIGGER_TYPES, REALTIME_NODE_TYPES } from './graph-utils';
7
8
  import { neutraliseIsLoggedInGates } from './is-logged-in-gate';
@@ -44,6 +45,21 @@ const DOM_TO_REACT_EVENT = {
44
45
  dragend: 'onDragEnd',
45
46
  drag: 'onDrag',
46
47
  };
48
+ /**
49
+ * Trigger types that run as LIFECYCLE code (no React event prop) but are still
50
+ * bound to ONE element, so the workflow only belongs on the page that renders
51
+ * it. Returns the DOM id to prune against, or null when the trigger is not
52
+ * element-scoped.
53
+ *
54
+ * Same fallback chain as the element-trigger branch: the HTML id first, the
55
+ * project-document node id only as a last resort.
56
+ */
57
+ const resolveLifecycleTriggerElementId = (triggerType, config) => {
58
+ if (triggerType !== 'event-element-visible') {
59
+ return null;
60
+ }
61
+ return (config.elementHtmlId || config.nodeId) || null;
62
+ };
47
63
  const getReactEventProp = (triggerType, config) => {
48
64
  switch (triggerType) {
49
65
  case 'event-element-clicked':
@@ -157,6 +173,8 @@ export const createNextWorkflowPlugin = (config) => {
157
173
  // Classify triggers into element-bound vs lifecycle
158
174
  const elementTriggers = [];
159
175
  const lifecycleWorkflows = [];
176
+ /** Lifecycle workflows bound to one element, for the per-page JSX prune. */
177
+ const lifecycleElementTargets = [];
160
178
  const stateChangeWorkflows = [];
161
179
  const globalStateChangeWorkflows = [];
162
180
  for (const wf of relevantWorkflows) {
@@ -199,6 +217,17 @@ export const createNextWorkflowPlugin = (config) => {
199
217
  }
200
218
  else {
201
219
  lifecycleWorkflows.push(wf);
220
+ // An element-scoped LIFECYCLE trigger (element-visible) has no React
221
+ // prop, so it lands here — and `lifecycleWorkflows` was activated
222
+ // unconditionally, bypassing the JSX-presence prune below that is the
223
+ // only thing scoping element workflows to one page. One cookie-consent
224
+ // check therefore shipped into EVERY generated file (17 per page in run
225
+ // a15472af, including 404.js and logo.js, which have no banner at all).
226
+ // Record its target so it is pruned like any other element trigger.
227
+ const lifecycleElementId = resolveLifecycleTriggerElementId(trigger.type, triggerConfig);
228
+ if (lifecycleElementId) {
229
+ lifecycleElementTargets.push({ workflowId: wf.id, elementId: lifecycleElementId });
230
+ }
202
231
  }
203
232
  }
204
233
  // Pre-scan: find which element triggers can be matched to JSX elements
@@ -208,8 +237,13 @@ export const createNextWorkflowPlugin = (config) => {
208
237
  let matchedElements = new Map();
209
238
  const matchedElementTriggers = [];
210
239
  const unmatchedElementTriggers = [];
211
- if (returnStatement && returnStatement.argument && elementTriggers.length > 0) {
212
- const targetIds = new Set(elementTriggers.map((t) => t.elementId));
240
+ if (returnStatement &&
241
+ returnStatement.argument &&
242
+ (elementTriggers.length > 0 || lifecycleElementTargets.length > 0)) {
243
+ const targetIds = new Set([
244
+ ...elementTriggers.map((t) => t.elementId),
245
+ ...lifecycleElementTargets.map((t) => t.elementId),
246
+ ]);
213
247
  matchedElements = findJSXElementsById(returnStatement.argument, targetIds);
214
248
  for (const et of elementTriggers) {
215
249
  if (matchedElements.has(et.elementId)) {
@@ -230,6 +264,13 @@ export const createNextWorkflowPlugin = (config) => {
230
264
  activeWorkflowIds.add(et.workflow.id);
231
265
  }
232
266
  for (const wf of lifecycleWorkflows) {
267
+ // A lifecycle workflow bound to a specific element is only active on the
268
+ // page that actually renders that element. One with no element target
269
+ // (page-loaded, interval, …) stays unconditionally active.
270
+ const target = lifecycleElementTargets.find((t) => t.workflowId === wf.id);
271
+ if (target && !matchedElements.has(target.elementId)) {
272
+ continue;
273
+ }
233
274
  activeWorkflowIds.add(wf.id);
234
275
  }
235
276
  for (const wf of stateChangeWorkflows) {
@@ -469,7 +510,14 @@ const defaultValueToLiteral = (val) => {
469
510
  }
470
511
  return types.nullLiteral();
471
512
  };
472
- const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
513
+ /**
514
+ * Object key for a state/global-state map that the workflow runtime looks up by
515
+ * the name written in the node config (`config.property`). The key therefore
516
+ * keeps the UIDL spelling ALWAYS — only the value beside it is a binding and
517
+ * gets sanitised. Reserved words are legal unquoted keys (`{ class: ... }`);
518
+ * anything that is not identifier syntax at all is quoted.
519
+ */
520
+ const stateMapKey = (name) => JSIdentifiers.isValidPropertyKeyName(name) ? types.identifier(name) : types.stringLiteral(name);
473
521
  const resolveStateDefinitionKey = (rawName, stateDefinitions) => {
474
522
  if (stateDefinitions[rawName]) {
475
523
  return rawName;
@@ -486,20 +534,29 @@ const injectWorkflowCode = (componentBody, stateDefinitions, matchedTriggers, ma
486
534
  const stateValueProperties = [];
487
535
  for (const [key, def] of Object.entries(stateDefinitions)) {
488
536
  const setterName = StringUtils.createStateStoringFunction(key);
489
- stateSetterProperties.push(types.objectProperty(types.identifier(key), types.identifier(setterName)));
490
- stateTypeProperties.push(types.objectProperty(types.identifier(key), types.stringLiteral(def.type || 'string')));
491
- stateValueProperties.push(types.objectProperty(types.identifier(key), types.identifier(key)));
537
+ // KEY: the name a workflow node's `config.property` is written against —
538
+ // never renamed. VALUE: the React binding declared by `createStateHookAST`,
539
+ // which is sanitised because a UIDL state may legally be called `class`.
540
+ stateSetterProperties.push(types.objectProperty(stateMapKey(key), types.identifier(setterName)));
541
+ stateTypeProperties.push(types.objectProperty(stateMapKey(key), types.stringLiteral(def.type || 'string')));
542
+ stateValueProperties.push(types.objectProperty(stateMapKey(key), types.identifier(JSIdentifiers.createSafeJSIdentifier(key))));
492
543
  }
493
544
  const globalStateStatements = [];
494
545
  if (globalStateDefinitions && Object.keys(globalStateDefinitions).length > 0) {
495
546
  const destructuredProps = [];
496
547
  for (const def of Object.values(globalStateDefinitions)) {
497
- const setterName = `set${capitalize(def.name)}`;
498
- destructuredProps.push(types.objectProperty(types.identifier(def.name), types.identifier(def.name), false, true));
499
- destructuredProps.push(types.objectProperty(types.identifier(setterName), types.identifier(setterName), false, true));
500
- stateSetterProperties.push(types.objectProperty(types.identifier(def.name), types.identifier(setterName)));
501
- stateTypeProperties.push(types.objectProperty(types.identifier(def.name), types.stringLiteral(def.type || 'string')));
502
- stateValueProperties.push(types.objectProperty(types.identifier(def.name), types.identifier(def.name)));
548
+ // `GlobalStateProvider` exposes every entry under its DECLARED name, so
549
+ // the context keys stay raw and only the locals we bind are sanitised.
550
+ // The pattern then reads `{ class: class_ }` — shorthand only when the
551
+ // two coincide, which is the case for every ordinary name.
552
+ const setterKey = StringUtils.createGlobalStateSetterName(def.name);
553
+ const setterName = JSIdentifiers.createSafeJSIdentifier(setterKey);
554
+ const localName = JSIdentifiers.createSafeJSIdentifier(def.name);
555
+ destructuredProps.push(types.objectProperty(stateMapKey(def.name), types.identifier(localName), false, localName === def.name));
556
+ destructuredProps.push(types.objectProperty(stateMapKey(setterKey), types.identifier(setterName), false, setterName === setterKey));
557
+ stateSetterProperties.push(types.objectProperty(stateMapKey(def.name), types.identifier(setterName)));
558
+ stateTypeProperties.push(types.objectProperty(stateMapKey(def.name), types.stringLiteral(def.type || 'string')));
559
+ stateValueProperties.push(types.objectProperty(stateMapKey(def.name), types.identifier(localName)));
503
560
  }
504
561
  // Always destructure refreshGlobalState for refreshFromDataSource support.
505
562
  // If no data source bindings exist, the context won't provide it, but
@@ -662,6 +719,12 @@ const injectWorkflowCode = (componentBody, stateDefinitions, matchedTriggers, ma
662
719
  existingExpr = existingAttr.value.expression;
663
720
  }
664
721
  else {
722
+ // A non-expression event prop (e.g. a stray `onClick=""` authored as a
723
+ // static attr) was never a callable listener — React throws
724
+ // `func.apply is not a function` on dispatch. Replace it with the
725
+ // workflow handler instead of skipping, which used to drop the
726
+ // trigger wiring silently AND ship the crashing prop.
727
+ openingElement.attributes[existingAttrIndex] = types.jSXAttribute(types.jSXIdentifier(reactProp), types.jSXExpressionContainer(wfHandlerExpr));
665
728
  continue;
666
729
  }
667
730
  // (event) => { existingHandler(event); __wfRef.current.elementTriggers[...](event); }
@@ -810,6 +873,9 @@ function __normalizeAdminFormRow(row, defaults) {
810
873
  id: s.id,
811
874
  env: s.env,
812
875
  hasStreamingAI: hasStreamingAINode(s),
876
+ // Every node in this segment runs fire-and-forget, so the browser
877
+ // dispatches it and carries on instead of waiting for the round trip.
878
+ fireAndForget: isFireAndForgetSegment(s),
813
879
  nodes: s.nodes.map((n) => ({
814
880
  id: n.id,
815
881
  type: n.type,
@@ -907,8 +973,26 @@ function __normalizeAdminFormRow(row, defaults) {
907
973
  lifecycleLines.push(code);
908
974
  }
909
975
  }
910
- // Lifecycle triggers
976
+ // Lifecycle triggers.
977
+ //
978
+ // `allWorkflows` here is the already-pruned `activeWorkflows`: a lifecycle
979
+ // element-visible trigger whose target element is NOT in this component's own
980
+ // JSX was excluded from it (its `__wfConfig_*` was therefore never declared).
981
+ // But `generateLifecycleTrigger` emits an IntersectionObserver that resolves
982
+ // its target at runtime with `document.getElementById(target)` — a
983
+ // DOCUMENT-WIDE lookup that happily matches an element ANOTHER component
984
+ // rendered (e.g. the shared "Cookie Consent" banner, which is attached to
985
+ // ~23 element-visible workflows and would otherwise ship into every product
986
+ // card). When it fires it calls `__execWf(__wfConfig_<id>, …)` for a config
987
+ // that was never emitted, throwing `ReferenceError: __wfConfig_… is not
988
+ // defined` the moment the element scrolls into view. Pruning the handler in
989
+ // lockstep with the config keeps the two in sync: the workflow still runs in
990
+ // the component/page that actually renders its target element.
991
+ const emittedConfigIds = new Set(allWorkflows.map((wf) => wf.id));
911
992
  for (const wf of lifecycleWorkflows) {
993
+ if (!emittedConfigIds.has(wf.id)) {
994
+ continue;
995
+ }
912
996
  const safeId = wf.id.replace(/[^a-zA-Z0-9]/g, '_');
913
997
  const code = generateLifecycleTrigger(wf, safeId);
914
998
  if (code) {
@@ -1428,16 +1512,23 @@ const generateLifecycleTrigger = (wf, safeId) => {
1428
1512
  ` cleanups.push(function() { Router.events.off('routeChangeComplete', __rc_${safeId}); });`);
1429
1513
  }
1430
1514
  case 'event-element-visible': {
1431
- const nodeId = config.nodeId;
1515
+ // `config.nodeId` is the PROJECT-DOCUMENT node id (`TQ_…`); no element in
1516
+ // the generated app ever carries it. `elementHtmlId` is the real DOM id
1517
+ // (`thq_container_…`), already stamped by `ensure-element-ids` and mapped
1518
+ // into the trigger config — the same fallback chain every other element
1519
+ // trigger uses above. Reading `nodeId` made `getElementById` return null,
1520
+ // so the observer was never constructed and the cookie-consent banner
1521
+ // could never appear on any page (run a15472af: 408 dead lookups).
1522
+ const elementId = (config.elementHtmlId || config.nodeId);
1432
1523
  const threshold = config.threshold || 0;
1433
1524
  const once = config.once;
1434
1525
  return (` // Element visible (${wf.name || wf.id})\n` +
1435
- ` const __visEl_${safeId} = document.getElementById('${nodeId}');\n` +
1526
+ ` const __visEl_${safeId} = document.getElementById('${elementId}');\n` +
1436
1527
  ` if (__visEl_${safeId}) {\n` +
1437
1528
  ` const __obs_${safeId} = new IntersectionObserver(function(entries) {\n` +
1438
1529
  ` entries.forEach(function(entry) {\n` +
1439
1530
  ` if (entry.isIntersecting) {\n` +
1440
- ` const triggerContext = { elementId: '${nodeId}', timestamp: Date.now(), intersectionRatio: entry.intersectionRatio };\n` +
1531
+ ` const triggerContext = { elementId: '${elementId}', timestamp: Date.now(), intersectionRatio: entry.intersectionRatio };\n` +
1441
1532
  ` ${execCall};\n` +
1442
1533
  (once ? ` __obs_${safeId}.disconnect();\n` : '') +
1443
1534
  ` }\n` +