@farm.js/react 0.1.0-beta.41 → 0.1.0-beta.42

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.
package/dist/vite.mjs CHANGED
@@ -153,7 +153,8 @@ var COMPILER_RUNTIME_FEATURE_EXPORTS = {
153
153
  "keyed-rows-complete-filter-prepend-hinted": "keyedRowsCompleteFilterPrependHintedRuntimeFeature",
154
154
  "keyed-ranges": "keyedRangesRuntimeFeature",
155
155
  "mixed-ranges": "mixedRangesRuntimeFeature",
156
- component: "componentRuntimeFeature"
156
+ component: "componentRuntimeFeature",
157
+ effects: "effectsRuntimeFeature"
157
158
  };
158
159
  function runtimeFeaturesForPlans(plans, keyedUpdateHints, keyedArrayFilterHints, keyedArrayStructuralAppendHints, keyedArrayStructuralAppendMapHints, keyedArrayPrependHints, keyedArrayStructuralPrependHints, keyedArrayStructuralPrependMapHints, keyedArrayPositionHints, keyedArrayBatchInsertHints, keyedArrayWindowReplaceHints, keyedArrayReorderHints, keyedArrayMapReorderHints, keyedArrayMappedRollingWindowChainHints, keyedArrayRollingWindowHints, keyedMapOrAppendHints, keyedArrayAppendOnlyHints) {
159
160
  const features = /* @__PURE__ */ new Set();
@@ -221,6 +222,106 @@ function isUseStateCall(expression, useStateNames, reactNames) {
221
222
  if (types.isIdentifier(expression.callee)) return useStateNames.has(expression.callee.name);
222
223
  return types.isMemberExpression(expression.callee) && !expression.callee.computed && types.isIdentifier(expression.callee.object) && reactNames.has(expression.callee.object.name) && types.isIdentifier(expression.callee.property, { name: "useState" });
223
224
  }
225
+ function reactHookCall(expression, hookNames, reactNames) {
226
+ if (!types.isCallExpression(expression)) return void 0;
227
+ const callee = expression.callee;
228
+ if (types.isIdentifier(callee)) return hookNames.get(callee.name);
229
+ return types.isMemberExpression(callee) && !callee.computed && types.isIdentifier(callee.object) && reactNames.has(callee.object.name) && types.isIdentifier(callee.property) && (callee.property.name === "useMemo" || callee.property.name === "useCallback" || callee.property.name === "useRef" || callee.property.name === "useEffect" || callee.property.name === "useLayoutEffect") ? callee.property.name : void 0;
230
+ }
231
+ function memoHookValue(expression, hookNames, reactNames) {
232
+ const hook = reactHookCall(expression, hookNames, reactNames);
233
+ if (hook !== "useMemo" && hook !== "useCallback") return void 0;
234
+ if (!types.isCallExpression(expression)) return void 0;
235
+ const [callback, dependencyList, ...rest] = expression.arguments;
236
+ if (rest.length > 0 || !types.isArrowFunctionExpression(callback) && !types.isFunctionExpression(callback) || callback.async || callback.generator) {
237
+ return `${hook} needs one inline synchronous callback`;
238
+ }
239
+ let dependencies;
240
+ if (dependencyList) {
241
+ if (!types.isArrayExpression(dependencyList) || !dependencyList.elements.every((element) => types.isIdentifier(element))) {
242
+ return `${hook} dependencies must be an array of names`;
243
+ }
244
+ dependencies = dependencyList.elements.map((element) => element.name);
245
+ }
246
+ if (hook === "useCallback") return { hook, value: callback, dependencies };
247
+ if (callback.params.length > 0) return "useMemo callbacks take no parameters";
248
+ const body = callback.body;
249
+ const value = types.isExpression(body) ? body : body.body.length === 1 && types.isReturnStatement(body.body[0]) && body.body[0].argument ? body.body[0].argument : void 0;
250
+ if (!value) return "useMemo callbacks must return one expression";
251
+ return { hook, value, dependencies };
252
+ }
253
+ function effectScope(path, effects, statesByValue, locals, propsParameter, stateParameter) {
254
+ const cell = (index, member) => types.memberExpression(
255
+ types.memberExpression(types.cloneNode(stateParameter), types.numericLiteral(index), true),
256
+ types.identifier(member)
257
+ );
258
+ const statements = [];
259
+ const parameter = path.node.params[0];
260
+ if (parameter && !types.isIdentifier(parameter)) {
261
+ statements.push(
262
+ types.variableDeclaration("const", [
263
+ types.variableDeclarator(types.cloneNode(parameter, true), types.cloneNode(propsParameter))
264
+ ])
265
+ );
266
+ }
267
+ const localsByName = new Map(locals.map((local) => [local.name, local]));
268
+ for (const statement of path.node.body.body) {
269
+ if (types.isFunctionDeclaration(statement)) {
270
+ statements.push(types.cloneNode(statement, true));
271
+ continue;
272
+ }
273
+ if (!types.isVariableDeclaration(statement)) continue;
274
+ const id = statement.declarations[0].id;
275
+ if (types.isArrayPattern(id)) {
276
+ const [value2, setter] = id.elements;
277
+ const index = statesByValue.get(value2.name).index;
278
+ statements.push(
279
+ types.variableDeclaration("const", [
280
+ types.variableDeclarator(types.identifier(value2.name), types.callExpression(cell(index, "get"), [])),
281
+ types.variableDeclarator(types.identifier(setter.name), cell(index, "set"))
282
+ ])
283
+ );
284
+ continue;
285
+ }
286
+ if (!types.isIdentifier(id)) continue;
287
+ const ref = statesByValue.get(id.name);
288
+ const local = localsByName.get(id.name);
289
+ const value = ref?.ref ? types.callExpression(cell(ref.index, "get"), []) : local ? types.cloneNode(local.value, true) : void 0;
290
+ if (value) {
291
+ statements.push(
292
+ types.variableDeclaration("const", [types.variableDeclarator(types.identifier(id.name), value)])
293
+ );
294
+ }
295
+ }
296
+ statements.push(
297
+ types.returnStatement(
298
+ types.arrayExpression(
299
+ effects.map(
300
+ (effect) => types.arrayExpression([
301
+ types.cloneNode(effect.callback, true),
302
+ effect.dependencies ? types.cloneNode(effect.dependencies, true) : types.identifier("undefined"),
303
+ ...effect.layout ? [types.booleanLiteral(true)] : []
304
+ ])
305
+ )
306
+ )
307
+ )
308
+ );
309
+ return types.blockStatement(statements);
310
+ }
311
+ function refReadDuringRender(root, refNames) {
312
+ let read;
313
+ traverse(expressionFile(cloneExpression(root)), {
314
+ Identifier(path) {
315
+ if (read || !refNames.has(path.node.name) || !path.isReferencedIdentifier()) return;
316
+ if (path.findParent((parent) => parent.isFunction())) return;
317
+ const attribute = path.parentPath?.isJSXExpressionContainer() ? path.parentPath.parentPath : void 0;
318
+ if (attribute?.isJSXAttribute() && jsxAttributeName(attribute.node) === "ref") return;
319
+ read = path.node.name;
320
+ path.stop();
321
+ }
322
+ });
323
+ return read;
324
+ }
224
325
  function cloneExpression(expression) {
225
326
  return types.cloneNode(expression, true);
226
327
  }
@@ -6519,13 +6620,18 @@ function lowerStableBindingTargets(root, bindings, blockRuntime, ownedElements)
6519
6620
  const visit = (element, path) => {
6520
6621
  const target = targetByPath.get(path.join("."));
6521
6622
  if (target !== void 0 && path.length > 0) {
6522
- element.openingElement.attributes.push(
6623
+ const attributes = element.openingElement.attributes;
6624
+ const userRefIndex = attributes.findIndex(
6625
+ (attribute) => types.isJSXAttribute(attribute) && jsxAttributeName(attribute) === "ref"
6626
+ );
6627
+ const userRef = userRefIndex >= 0 ? attributes.splice(userRefIndex, 1)[0].value.expression : void 0;
6628
+ attributes.push(
6523
6629
  types.jsxAttribute(
6524
6630
  types.jsxIdentifier("ref"),
6525
6631
  types.jsxExpressionContainer(
6526
6632
  types.callExpression(
6527
6633
  types.memberExpression(types.cloneNode(blockRuntime), types.identifier("target")),
6528
- [types.numericLiteral(target)]
6634
+ [types.numericLiteral(target), ...userRef && types.isExpression(userRef) ? [userRef] : []]
6529
6635
  )
6530
6636
  )
6531
6637
  )
@@ -6584,9 +6690,14 @@ function analyzeHostTree(root, statesByValue, safeGlobals, conditionalExpression
6584
6690
  const name = jsxAttributeName(attribute);
6585
6691
  if (!name) return "namespaced JSX attributes are not supported yet";
6586
6692
  if (name === "is") return "customized built-in elements require React ownership";
6587
- if (name === "ref" || name === "dangerouslySetInnerHTML") {
6588
- return `${name} requires React ownership`;
6693
+ if (name === "ref") {
6694
+ const value = types.isJSXExpressionContainer(attribute.value) ? attribute.value.expression : void 0;
6695
+ if (path.length > 0 && types.isIdentifier(value) && statesByValue.get(value.name)?.ref) {
6696
+ continue;
6697
+ }
6698
+ return "ref requires React ownership";
6589
6699
  }
6700
+ if (name === "dangerouslySetInnerHTML") return `${name} requires React ownership`;
6590
6701
  if (!types.isJSXExpressionContainer(attribute.value) || types.isJSXEmptyExpression(attribute.value.expression)) {
6591
6702
  continue;
6592
6703
  }
@@ -6821,7 +6932,7 @@ function wrapperElement(definitionIdentifier, props) {
6821
6932
  const attributes = props ? [types.jsxSpreadAttribute(types.cloneNode(props))] : [];
6822
6933
  return types.jsxElement(types.jsxOpeningElement(name, attributes, true), null, [], true);
6823
6934
  }
6824
- function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateIdentifier, keyedArrayAppendIdentifier, keyedArrayFilterIdentifier, keyedArrayMapPipelineIdentifier, keyedArrayMappedStructuralAppendIdentifier, keyedArrayStructuralAppendMapPipelineIdentifier, keyedArrayMappedStructuralPrependIdentifier, keyedArrayStructuralPrependMapPipelineIdentifier, keyedArrayQueuedMapPipelineIdentifier, keyedArrayRollingWindowMapPipelineIdentifier, keyedArrayMappedRollingWindowIdentifier, keyedArrayMapReorderIdentifier, keyedArrayMappedStructuralIdentifier, keyedArrayPrependIdentifier, keyedArrayPositionIdentifier, keyedArrayBatchInsertIdentifier, keyedArrayWindowReplaceIdentifier, keyedArrayReorderIdentifier, keyedArrayStructuralReorderIdentifier, keyedArraySortIdentifier, keyedArrayStructuralSortIdentifier, keyedArrayRollingWindowIdentifier, keyedArraySliceIdentifier, keyedCollectionUpdateIdentifier, keyedCollectionMutationIdentifier, runtimeFeatureIdentifiers, usedRuntimeFeatures, optimizationCounts, compilerUsage, useStateNames, reactNames, listNames, moduleId, reactivity, delegateWithoutReact) {
6935
+ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateIdentifier, keyedArrayAppendIdentifier, keyedArrayFilterIdentifier, keyedArrayMapPipelineIdentifier, keyedArrayMappedStructuralAppendIdentifier, keyedArrayStructuralAppendMapPipelineIdentifier, keyedArrayMappedStructuralPrependIdentifier, keyedArrayStructuralPrependMapPipelineIdentifier, keyedArrayQueuedMapPipelineIdentifier, keyedArrayRollingWindowMapPipelineIdentifier, keyedArrayMappedRollingWindowIdentifier, keyedArrayMapReorderIdentifier, keyedArrayMappedStructuralIdentifier, keyedArrayPrependIdentifier, keyedArrayPositionIdentifier, keyedArrayBatchInsertIdentifier, keyedArrayWindowReplaceIdentifier, keyedArrayReorderIdentifier, keyedArrayStructuralReorderIdentifier, keyedArraySortIdentifier, keyedArrayStructuralSortIdentifier, keyedArrayRollingWindowIdentifier, keyedArraySliceIdentifier, keyedCollectionUpdateIdentifier, keyedCollectionMutationIdentifier, runtimeFeatureIdentifiers, usedRuntimeFeatures, optimizationCounts, compilerUsage, useStateNames, hookNames, reactNames, listNames, moduleId, reactivity, delegateWithoutReact) {
6825
6936
  const { path, name, statementPath } = candidate;
6826
6937
  if (path.node.async || path.node.generator)
6827
6938
  return "async and generator components are not supported";
@@ -6836,6 +6947,8 @@ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateId
6836
6947
  const globalCollections = new Set(["Set", "Map"].filter((name2) => !path.scope.getBinding(name2)));
6837
6948
  const states = [];
6838
6949
  const locals = [];
6950
+ const effects = [];
6951
+ const memoDeclarations = [];
6839
6952
  let returned;
6840
6953
  for (const statement of path.node.body.body) {
6841
6954
  if (types.isReturnStatement(statement)) {
@@ -6843,6 +6956,25 @@ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateId
6843
6956
  returned = statement;
6844
6957
  continue;
6845
6958
  }
6959
+ if (types.isExpressionStatement(statement)) {
6960
+ const hook = reactHookCall(statement.expression, hookNames, reactNames);
6961
+ if (hook === "useEffect" || hook === "useLayoutEffect") {
6962
+ const [callback, dependencyList, ...rest] = statement.expression.arguments;
6963
+ if (rest.length > 0 || !types.isArrowFunctionExpression(callback) && !types.isFunctionExpression(callback) || callback.async || callback.generator || callback.params.length > 0) {
6964
+ return `${hook} needs one inline synchronous callback`;
6965
+ }
6966
+ if (containsDirectHookCall(callback)) return `Hooks cannot be called inside ${hook}`;
6967
+ if (dependencyList && (!types.isArrayExpression(dependencyList) || !dependencyList.elements.every((element) => types.isIdentifier(element)))) {
6968
+ return `${hook} dependencies must be an array of names`;
6969
+ }
6970
+ effects.push({
6971
+ callback,
6972
+ dependencies: dependencyList,
6973
+ layout: hook === "useLayoutEffect"
6974
+ });
6975
+ continue;
6976
+ }
6977
+ }
6846
6978
  if (types.isFunctionDeclaration(statement)) {
6847
6979
  if (!statement.id) return "named event handler declarations must have a name";
6848
6980
  if (statement.generator || statement.typeParameters) {
@@ -6875,21 +7007,47 @@ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateId
6875
7007
  if (!types.isIdentifier(declaration.id) || !types.isExpression(declaration.init)) {
6876
7008
  return "derived const values and event handlers must use one identifier and one expression";
6877
7009
  }
6878
- if (types.isArrowFunctionExpression(declaration.init) || types.isFunctionExpression(declaration.init)) {
6879
- if (declaration.init.generator) {
7010
+ let init = declaration.init;
7011
+ if (reactHookCall(init, hookNames, reactNames) === "useRef") {
7012
+ const [initial, ...rest] = init.arguments;
7013
+ if (rest.length > 0 || initial && !types.isExpression(initial)) {
7014
+ return "useRef takes at most one initial value";
7015
+ }
7016
+ states.push({
7017
+ valueName: declaration.id.name,
7018
+ setterName: path.scope.generateUidIdentifier("farmRef").name,
7019
+ index: states.length,
7020
+ initialValue: types.objectExpression([
7021
+ types.objectProperty(
7022
+ types.identifier("current"),
7023
+ initial ? initial : types.identifier("undefined")
7024
+ )
7025
+ ]),
7026
+ ref: true
7027
+ });
7028
+ continue;
7029
+ }
7030
+ const memo = memoHookValue(init, hookNames, reactNames);
7031
+ if (typeof memo === "string") return memo;
7032
+ if (memo) {
7033
+ memoDeclarations.push({ name: declaration.id.name, ...memo });
7034
+ init = memo.value;
7035
+ }
7036
+ if (types.isArrowFunctionExpression(init) || types.isFunctionExpression(init)) {
7037
+ if (init.generator) {
6880
7038
  return `event handler ${declaration.id.name} cannot be a generator`;
6881
7039
  }
6882
7040
  locals.push({
6883
7041
  kind: "handler",
6884
7042
  name: declaration.id.name,
6885
- value: declaration.init,
7043
+ value: init,
6886
7044
  statesBefore: states.length
6887
7045
  });
6888
7046
  } else {
6889
7047
  locals.push({
6890
7048
  kind: "derived",
6891
7049
  name: declaration.id.name,
6892
- value: declaration.init,
7050
+ value: init,
6893
7051
  statesBefore: states.length
6894
7052
  });
6895
7053
  }
@@ -6902,6 +7060,32 @@ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateId
6902
7060
  const statesBySetter = new Map(states.map((state) => [state.setterName, state]));
6903
7061
  const localNames = new Set(locals.map((binding) => binding.name));
6904
7062
  if (localNames.size !== locals.length) return "local binding names must be unique";
7063
+ const reactiveNames = [
7064
+ ...states.map((state) => state.valueName),
7065
+ ...propsPlan.destructuredNames,
7066
+ ...propsPlan.wrapperProps ? [propsPlan.definitionParameter.name] : [],
7067
+ ...localNames
7068
+ ];
7069
+ for (const memo of memoDeclarations) {
7070
+ if (!memo.dependencies) continue;
7071
+ const listed = new Set(memo.dependencies);
7072
+ const missing = reactiveNames.find(
7073
+ (name2) => name2 !== memo.name && !listed.has(name2) && referencesIdentifier(memo.value, name2)
7074
+ );
7075
+ if (missing) {
7076
+ return `${memo.hook} ${memo.name} reads ${missing} without listing it as a dependency`;
7077
+ }
7078
+ }
7079
+ const refNames = new Set(states.filter((state) => state.ref).map((state) => state.valueName));
7080
+ if (refNames.size > 0) {
7081
+ for (const binding of locals) {
7082
+ if (binding.kind !== "derived") continue;
7083
+ const ref2 = [...refNames].find((name2) => referencesIdentifier(binding.value, name2));
7084
+ if (ref2) return `derived local ${binding.name} cannot read the ref ${ref2} during render`;
7085
+ }
7086
+ const ref = refReadDuringRender(returned.argument, refNames);
7087
+ if (ref) return `the ref ${ref} cannot be read during render`;
7088
+ }
6905
7089
  for (const state of states) {
6906
7090
  if (state.initialValue && (collectStateDependencies(state.initialValue, statesByValue).length > 0 || collectReferencedLocals(state.initialValue, localNames).length > 0 || [...statesBySetter].some(
6907
7091
  ([setterName]) => referencesIdentifier(state.initialValue, setterName)
@@ -7844,6 +8028,7 @@ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateId
7844
8028
  appliedKeyedMapUpdateHints > 0 || appliedKeyedArrayAppendHints > 0,
7845
8029
  appliedKeyedArrayAppendHints > 0 && appliedKeyedMapUpdateHints === 0
7846
8030
  );
8031
+ if (effects.length > 0) runtimeFeatures.push("effects");
7847
8032
  for (const feature of runtimeFeatures) {
7848
8033
  if (!runtimeFeatureIdentifiers.has(feature)) {
7849
8034
  runtimeFeatureIdentifiers.set(
@@ -7948,6 +8133,15 @@ function compileCandidate(candidate, createComponentIdentifier, keyedMapUpdateId
7948
8133
  rewrittenRoot
7949
8134
  )
7950
8135
  ),
8136
+ ...effects.length > 0 ? [
8137
+ types.objectProperty(
8138
+ types.identifier("effects"),
8139
+ types.arrowFunctionExpression(
8140
+ [types.cloneNode(propsParameter), types.cloneNode(stateParameter)],
8141
+ effectScope(path, effects, statesByValue, locals, propsParameter, stateParameter)
8142
+ )
8143
+ )
8144
+ ] : [],
7951
8145
  types.objectProperty(
7952
8146
  types.identifier("bindings"),
7953
8147
  types.arrayExpression(
@@ -8058,6 +8252,7 @@ async function compileReactModule(code, id, options) {
8058
8252
  const moduleDirectives = new Set(directiveValues(programPath.node));
8059
8253
  markForeignContent(programPath);
8060
8254
  const useStateNames = /* @__PURE__ */ new Set();
8255
+ const hookNames = /* @__PURE__ */ new Map();
8061
8256
  const reactNames = /* @__PURE__ */ new Set();
8062
8257
  const listNames = /* @__PURE__ */ new Set();
8063
8258
  for (const statement of programPath.node.body) {
@@ -8076,6 +8271,8 @@ async function compileReactModule(code, id, options) {
8076
8271
  reactNames.add(specifier.local.name);
8077
8272
  } else if (types.isImportSpecifier(specifier) && types.isIdentifier(specifier.imported, { name: "useState" })) {
8078
8273
  useStateNames.add(specifier.local.name);
8274
+ } else if (types.isImportSpecifier(specifier) && types.isIdentifier(specifier.imported) && (specifier.imported.name === "useMemo" || specifier.imported.name === "useCallback" || specifier.imported.name === "useRef" || specifier.imported.name === "useEffect" || specifier.imported.name === "useLayoutEffect")) {
8275
+ hookNames.set(specifier.local.name, specifier.imported.name);
8079
8276
  }
8080
8277
  }
8081
8278
  }
@@ -8201,6 +8398,7 @@ async function compileReactModule(code, id, options) {
8201
8398
  optimizationCounts,
8202
8399
  compilerUsage,
8203
8400
  useStateNames,
8401
+ hookNames,
8204
8402
  reactNames,
8205
8403
  listNames,
8206
8404
  id,