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