diff --git a/.changeset/soft-meals-travel.md b/.changeset/soft-meals-travel.md
new file mode 100644
index 000000000..a845151cc
--- /dev/null
+++ b/.changeset/soft-meals-travel.md
@@ -0,0 +1,2 @@
+---
+---
diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml
deleted file mode 100644
index 9b7fcf1d5..000000000
--- a/.github/workflows/canary.yml
+++ /dev/null
@@ -1,83 +0,0 @@
-name: Canary
-
-on: pull_request
-
-jobs:
- release:
- runs-on: ubuntu-latest
- steps:
- # We store information about used changeset in the comment
- # So we need to find it to check if we need to publish a new canary release
- # Also we will update this comment with new information in case of new canary release
- - name: Find comment about previous canary release
- uses: peter-evans/find-comment@v1
- id: find_comment
- with:
- issue-number: ${{ github.event.pull_request.number }}
- comment-author: 'github-actions[bot]'
- body-includes: Farfetched Canary
- - uses: actions/checkout@v3
- - uses: pnpm/action-setup@v2
- - uses: actions/setup-node@v3
- with:
- node-version-file: '.nvmrc'
- cache: 'pnpm'
- - name: Authenticate with NPM
- run: |
- echo "//registry.npmjs.org/:_authToken="${{secrets.NPM_TOKEN}}"" > ~/.npmrc
- - run: pnpm install --frozen-lockfile
- # Parse latest published version of the canary release and update local package.json for all packages
- - name: Restore canary release version
- run: node ./tools/scripts/canary/canary_version_restore.mjs ${{ github.event.pull_request.number }}
- # Update version in package.json for all packages with changeset and generate pre.json file
- - run: pnpm changeset pre enter ${{ github.event.pull_request.number }}
- - run: pnpm changeset version
- - run: pnpm changeset pre exit
- # Check if we need to publish a new canary release
- # it uses pre.json file and information about previous canary relase from the comment
- - name: Check if new canary release is required
- id: canary_required
- run: node ./tools/scripts/canary/canary_required.mjs """${{ steps.find_comment.outputs.comment-body }}""" >> $GITHUB_OUTPUT && cat $GITHUB_OUTPUT
- - name: Prepare package names
- if: steps.canary_required.outputs.skipCanary == ''
- run: node ./tools/scripts/canary/canary_name_change.mjs
- - name: Publish canary release
- if: steps.canary_required.outputs.skipCanary == ''
- run: pnpm -r publish --no-git-checks
- - name: Retrieve information about latest canary release
- id: canary_info
- run: node ./tools/scripts/canary/canary_info.mjs >> $GITHUB_OUTPUT && cat $GITHUB_OUTPUT
- # In case of absence of the comment we will create it with information about latest canary release
- - name: Create comment
- if: steps.find_comment.outputs.comment-id == ''
- uses: peter-evans/create-or-update-comment@v1
- with:
- issue-number: ${{ github.event.pull_request.number }}
- body: |
- # Farfetched Canary
-
- Latest canary version is ${{ steps.canary_info.outputs.canaryVersion }}
-
- [More information about canary versions](https://ff.effector.dev/releases/canary.html)
-
- ---
-
- Used changeset: ${{ steps.canary_info.outputs.usedChangesets }}
- # Otherwise we will update it with information about latest caanry release,
- # but only if we published a new canary release
- - name: Update comment
- if: steps.find_comment.outputs.comment-id != '' && steps.canary_required.outputs.skipCanary == ''
- uses: peter-evans/create-or-update-comment@v1
- with:
- edit-mode: replace
- comment-id: ${{ steps.find_comment.outputs.comment-id }}
- body: |
- # Farfetched Canary
-
- Latest canary version is ${{ steps.canary_info.outputs.canaryVersion }}
-
- [More information about canary versions](https://ff.effector.dev/releases/canary.html)
-
- ---
-
- Used changeset: ${{ steps.canary_info.outputs.usedChangesets }}
diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml
deleted file mode 100644
index 23fff17b3..000000000
--- a/.github/workflows/website.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-name: Website
-
-on: [push]
-
-jobs:
- website:
- runs-on: ubuntu-latest
- permissions:
- contents: read
- deployments: write
- name: Publish to Cloudflare Pages
- steps:
- - uses: actions/checkout@v3
- with:
- fetch-depth: 0
- - uses: pnpm/action-setup@v2
- - uses: actions/setup-node@v3
- with:
- node-version-file: '.nvmrc'
- cache: 'pnpm'
- - run: pnpm install --frozen-lockfile
-
- - run: pnpm run -r build
-
- - name: Publish to Cloudflare Pages
- uses: cloudflare/pages-action@v1
- with:
- apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- accountId: 1d6db711ad880b2455da08a6aeb2a119
- projectName: farfetched
- directory: apps/website/docs/.vitepress/dist
- gitHubToken: ${{ secrets.GITHUB_TOKEN }}
diff --git a/README.md b/README.md
index 8f5b145e0..75502c420 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,5 @@ Special thanks to all contributors and especially [Alexandr](https://github.com/
Some of external libraries were inlined to Farfetched due to bundle size and custom features requirements:
- https://github.com/effector/patronum
-- https://github.com/emn178/js-sha1/blob/master/tests/test.js
-- http://www.movable-type.co.uk/scripts/sha1.html
- https://github.com/smelukov/nano-equal
- https://github.com/DirtyHairy/async-mutex
diff --git a/apps/website/changelog/cli.mjs b/apps/website/changelog/cli.mjs
index 2622b73b0..585067cc0 100644
--- a/apps/website/changelog/cli.mjs
+++ b/apps/website/changelog/cli.mjs
@@ -77,11 +77,11 @@ function mergeChangelogs(packages) {
)) {
const logForVersion = [];
for (const { name: packageName, changes: packageChanges } of packages) {
- const pacakgeChangesEntries = Object.entries(packageChanges)
+ const packageChangesEntries = Object.entries(packageChanges)
.map(([type, items]) => [type, excludeTrashUpdates(items)])
.filter(([, items]) => items.length > 0);
- let hasChanges = pacakgeChangesEntries.length > 0;
+ let hasChanges = packageChangesEntries.length > 0;
if (!hasChanges) {
continue;
@@ -89,7 +89,7 @@ function mergeChangelogs(packages) {
logForVersion.push(['para', `::: details ${packageName}`]);
- for (const [type, items] of pacakgeChangesEntries) {
+ for (const [type, items] of packageChangesEntries) {
logForVersion.push(['para', ['strong', type]], ...items);
}
diff --git a/apps/website/docs/.vitepress/config.js b/apps/website/docs/.vitepress/config.js
index 81d1a913e..b7f0bd512 100644
--- a/apps/website/docs/.vitepress/config.js
+++ b/apps/website/docs/.vitepress/config.js
@@ -330,7 +330,6 @@ export default withMermaid(
text: 'Deep dive',
collapsed: false,
items: [
- { text: 'Unique store identifiers', link: '/recipes/sids' },
{
text: 'Data flow in Remote Operation',
link: '/recipes/data_flow',
@@ -366,11 +365,11 @@ export default withMermaid(
items: [
{
text: 'SolidJS',
- link: 'https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase/solid-real-world-rick-morty',
+ link: 'https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase-solid-real-world-rick-morty',
},
{
text: 'React and React Router',
- link: 'https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase/react-real-world-pokemons',
+ link: 'https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase-react-real-world-pokemons',
},
{
text: 'Next.js',
@@ -378,7 +377,7 @@ export default withMermaid(
},
{
text: 'Forest',
- link: 'https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase/forest-real-world-breaking-bad',
+ link: 'https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase-forest-real-world-breaking-bad',
},
],
},
diff --git a/apps/website/docs/api/contracts/runtypes.md b/apps/website/docs/api/contracts/runtypes.md
index 6b34e7c83..de692b192 100644
--- a/apps/website/docs/api/contracts/runtypes.md
+++ b/apps/website/docs/api/contracts/runtypes.md
@@ -20,9 +20,9 @@ npm install runtypes @farfetched/runtypes
## Showcases
-- [Real-world showcase with SolidJS around JSON API](https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase/solid-real-world-rick-morty/)
-- [Real-world showcase with React around JSON API](https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase/react-real-world-pokemons/)
-- [Real-world showcase with Forest around JSON API](https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase/forest-real-world-breaking-bad/)
+- [Real-world showcase with SolidJS around JSON API](https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase-solid-real-world-rick-morty/)
+- [Real-world showcase with React around JSON API](https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase-react-real-world-pokemons/)
+- [Real-world showcase with Forest around JSON API](https://github.com/igorkamyshev/farfetched/tree/master/apps/showcase-forest-real-world-breaking-bad/)
## `runtypeContract`
diff --git a/apps/website/docs/api/factories/create_barrier.md b/apps/website/docs/api/factories/create_barrier.md
index b9338badc..0253c0c29 100644
--- a/apps/website/docs/api/factories/create_barrier.md
+++ b/apps/website/docs/api/factories/create_barrier.md
@@ -24,12 +24,12 @@ Configuration fields:
### `createBarrier({ activateOn, perform })`
```ts
-import { createBarrier, isHttpError } from '@farfetched/core';
+import { createBarrier, isHttpErrorCode } from '@farfetched/core';
import { combine } from 'effector';
const authBarrier = createBarrier({
activateOn: {
- failure: isHttpError(401),
+ failure: isHttpErrorCode(401),
},
perform: [renewTokenMutationFx],
});
diff --git a/apps/website/docs/api/primitives/query.md b/apps/website/docs/api/primitives/query.md
index 94031aed4..2cf57c53c 100644
--- a/apps/website/docs/api/primitives/query.md
+++ b/apps/website/docs/api/primitives/query.md
@@ -6,6 +6,15 @@ outline: [2, 3]
Representation of a piece of remote data.
+::: info Rule of thumb:
+
+- some piece of data is stored in a remote location (like a server)
+- its local representation can be be easily deleted and re-fetched from the remote location
+
+So, it is a good candidate for a _Query_.
+
+:::
+
## Commands
This section describes the [_Event_](https://effector.dev/en/api/effector/event/) that can be used to perform actions on the _Query_. Commands should be called in application code.
diff --git a/apps/website/docs/recipes/cache.md b/apps/website/docs/recipes/cache.md
index ead582aba..757a62b85 100644
--- a/apps/website/docs/recipes/cache.md
+++ b/apps/website/docs/recipes/cache.md
@@ -30,7 +30,7 @@ To achieve this, Every [_Query_](/api/primitives/query) exposes `.__.lowLevelAPI
## Cache key generation
-[`cache`](/api/operators/cache) does not require any manual key generation to work, it uses the [SID](/recipes/sids) of the [_Query_](/api/primitives/query) and all external [_Stores_](https://effector.dev/en/api/effector/store/) that affect [_Query_](/api/primitives/query) to create a unique identifier for every cache entry. It means, key generation is fully automatic, and you don't need to worry about it.
+[`cache`](/api/operators/cache) does not require any manual key generation to work, it uses the [SID](https://effector.dev/en/explanation/sids/) of the [_Query_](/api/primitives/query) and all external [_Stores_](https://effector.dev/en/api/effector/store/) that affect [_Query_](/api/primitives/query) to create a unique identifier for every cache entry. It means, key generation is fully automatic, and you don't need to worry about it.
### Sources extraction
@@ -86,7 +86,7 @@ Static nature of [Effector](/statements/effector) allows us to perform this tran
### SID
-Every [_Query_](/api/primitives/query) has a unique identifier — [SID](/recipes/sids). Effector provides a couple of plugins for automatic SIDs generation.
+Every [_Query_](/api/primitives/query) has a unique identifier — [SID](https://effector.dev/en/explanation/sids/). Effector provides a couple of plugins for automatic SIDs generation.
@@ -98,10 +98,10 @@ So, the key is a hash of the following data:
- `params` of the particular call of the [_Query_](/api/primitives/query)
- current values of all external [_Stores_](https://effector.dev/en/api/effector/store/) that affect [_Query_](/api/primitives/query)
-To get short and unique key, we stringify all data, concatenate it and then hash it with [SHA-1](https://en.wikipedia.org/wiki/SHA-1).
+To get short and unique key, we stringify all data, concatenate it and then hash it with [custom hash function](https://github.com/igorkamyshev/farfetched/blob/master/packages/core/src/cache/lib/hash.ts).
:::tip
-SHA-1 is a [cryptographically broken](https://blog.mozilla.org/security/2017/02/23/the-end-of-sha-1-on-the-public-web/), but we use it for key generation only, so it is safe to use it in this case.
+It is a cryptographically broken, but we use it for key generation only, so it is safe to use it in this case.
:::
## Adapter replacement
diff --git a/apps/website/docs/recipes/form_data.md b/apps/website/docs/recipes/form_data.md
index 4c562de1b..abc465d9e 100644
--- a/apps/website/docs/recipes/form_data.md
+++ b/apps/website/docs/recipes/form_data.md
@@ -159,7 +159,7 @@ const uploadPhotoMutation = createUploadFileMutation();
### SSR, `cache` and DevTools support
::: tip Deep dive
-If you want to learn more about the reasons behind this requirement, please read [this article](/recipes/sids).
+If you want to learn more about the reasons behind this requirement, please read [this article](https://effector.dev/en/explanation/sids/).
:::
If you use Farfetched in SSR, want to use [DevTools](/tutorial/devtools) or [`cache`](/api/operators/cache), you need to provide a unique name for each [_Mutation_](/api/primitives/mutation). It can be done by passing the `name` option to the [`createMutation`](/api/factories/create_mutation) factory:
diff --git a/apps/website/docs/recipes/graphql_query.md b/apps/website/docs/recipes/graphql_query.md
index ffed955fa..ee4c57244 100644
--- a/apps/website/docs/recipes/graphql_query.md
+++ b/apps/website/docs/recipes/graphql_query.md
@@ -29,7 +29,7 @@ function createGraphQLQuery(config) {
```
:::tip
-Do not forget to add path of the factory to a factories list in the [code transformations configuration](/recipes/sids).
+Do not forget to add path of the factory to a factories list in the [code transformations configuration](https://effector.dev/en/explanation/sids/).
:::
Now, we have to write code with mapping from config of `createGraphQLQuery` to config of `createJsonQuery`.
diff --git a/apps/website/docs/recipes/no_fetch.md b/apps/website/docs/recipes/no_fetch.md
index 062f35a0d..c61b81025 100644
--- a/apps/website/docs/recipes/no_fetch.md
+++ b/apps/website/docs/recipes/no_fetch.md
@@ -36,8 +36,8 @@ import { createMutation } from '@farfetched/core';
import axios from 'axios';
const loginMutation = createMutation({
- async handler({ login, password } {
- const response = await axios.post('/login', { login, password })
+ async handler({ login, password }) {
+ const response = await axios.post('/login', { login, password });
return response.data;
},
diff --git a/apps/website/docs/recipes/server_cache.md b/apps/website/docs/recipes/server_cache.md
index 5f1074e48..dc62e79a8 100644
--- a/apps/website/docs/recipes/server_cache.md
+++ b/apps/website/docs/recipes/server_cache.md
@@ -10,7 +10,7 @@ Let's talk about [caching](/tutorial/caching) and [SSR](/recipes/ssr) in the sin
## Pre-requisites
-Do not forget that [`cache`](/api/operators/cache) operator requires setting up [SIDs](/recipes/sids) in your application. It can be done by using code transformation tools.
+Do not forget that [`cache`](/api/operators/cache) operator requires setting up [SIDs](https://effector.dev/en/explanation/sids/) in your application. It can be done by using code transformation tools.
diff --git a/apps/website/docs/recipes/sids.md b/apps/website/docs/recipes/sids.md
index 2ac0f0221..1cf9ff009 100644
--- a/apps/website/docs/recipes/sids.md
+++ b/apps/website/docs/recipes/sids.md
@@ -1,228 +1,3 @@
# SIDs
-Farfetched [uses Effector](/statements/effector) that is based on idea of atomic store. It means that any application does not have some centralized state controller or other entry point to collect all states in one place.
-
-So, there is the question — how to distinguish units between different environments? For example, if we ran an application on the server and serialize its state to JSON, how do we know which part of the JSON should be filled in a particular store on the client?
-
-Let's discuss how this problem solved by other state managers.
-
-## Other state managers
-
-### Single store
-
-In the state manager with single store (e.g. Redux), this problem does not exist at all. It is a single store, which can be serialized and deserialized without any additional information.
-
-:::info
-Actually, single store forces you to create unique names of each part of it implicitly. In any object you won't be able to create duplicate keys, so the path to store slice is a unique identifier of this slice.
-:::
-
-```ts
-// server.ts
-import { createStore } from 'single-store-state-manager';
-
-function handlerRequest() {
- const store = createStore({ initialValue: null });
-
- return {
- // It is possible to just serialize the whole store
- state: JSON.stringify(store.getState()),
- };
-}
-
-// client.ts
-import { createStore } from 'single-store-state-manager';
-
-// Let's assume that server put the state into the HTML
-const serverState = readServerStateFromWindow();
-
-const store = createStore({
- // Just parse the whole state and use it as client state
- initialValue: JSON.parse(serverState),
-});
-```
-
-It's great that you do not need any additional tools for serialization and deserialization, but single store has a few problems:
-
-- It does not support tree-shaking and code-splitting, you have to load the whole store anyway
-- Because its architecture, it requires some additional tools for fixing performance (like `reselect`)
-- It does not support any kind of micro-frontends and stuff which is getting bigger recently
-
-### Multi stores
-
-Unfortunately, state managers that built around idea of multi stores do not solve this problem good. Some tools offer single store like solutions (MobX), some does not try to solve this issue at all (Recoil, Zustand).
-
-:::info
-E.g., the common pattern to solve serialization problem in MobX is [Root Store Pattern](https://dev.to/ivandotv/mobx-root-store-pattern-with-react-hooks-318d) which is destroying the whole idea of multi stores.
-:::
-
-So, we are considering SSR as a first class citizen of modern web applications, and we are going to support code-splitting or micro-frontends. It is the reason why Farfetched uses [Effector under the hood](/statements/effector).
-
-## Unique identifiers for every store
-
-Because of multi-store architecture, Effector requires a unique identifier for every store. It is a string that is used to distinguish stores between different environments. In Effector's world this kind of strings are called `sid`.
-
-:::tip TL;DR
-
-`sid` is a unique identifier of a store. It is used to distinguish stores between different environments.
-
-:::
-
-Let's add it to some stores:
-
-```ts
-const $name = createStore(null, { sid: 'name' });
-const $age = createStore(null, { sid: 'age' });
-```
-
-Now, we can serialize and deserialize stores:
-
-```ts
-// server.ts
-async function handlerRequest() {
- // create isolated instance of application
- const scope = fork();
-
- // fill some data to stores
- await allSettled($name, { scope, params: 'Igor' });
- await allSettled($age, { scope, params: 25 });
-
- const state = JSON.serialize(serialize(scope));
- // -> { "name": "Igor", "age": 25 }
-
- return { state };
-}
-```
-
-After this code, we have a serialized state of our application. It is a plain object with stores' values. We can put it back to the stores on the client:
-
-```ts
-// Let's assume that server put the state into the HTML
-const serverState = readServerStateFromWindow();
-
-const scope = fork({
- // Just parse the whole state and use it as client state
- values: JSON.parse(serverState),
-});
-```
-
-Of course, it's a lot of boring jobs to write `sid` for every store. Effector provides a way to do it automatically with code transformation plugins.
-
-## Plugins for code transformations
-
-
-
-## How plugins work under the hood
-
-Both plugins use the same approach to code transformation. Basically they do two things:
-
-1. add `sid`-s and meta-information to raw Effector's units creation, like `createStore` or `createUnit`
-2. wrap custom factories with `withFactory` helper that allow to make `sid`-s of inner units unique as well
-
-Let's take a look at the first point. For the following source code:
-
-```ts
-const $name = createStore(null);
-```
-
-Plugin will apply these transformations:
-
-```ts
-const $name = createStore(null, { sid: 'j3l44' });
-```
-
-:::tip
-Plugins create `sid`-s as a hash of the file path and the line number where the unit was created. It allows making `sid`-s unique and stable.
-:::
-
-So, the second point is about custom factories. For example, we have a custom factory for creating stores:
-
-```ts
-function nameStore() {
- const $name = createStore(null);
-
- return { $name };
-}
-
-const personOne = nameStore();
-const personTwo = nameStore();
-```
-
-First, plugin will add `sid`-s to inner units:
-
-```ts
-function nameStore() {
- const $name = createStore(null, { sid: 'ffds2' });
-
- return { $name };
-}
-
-const personOne = nameStore();
-const personTwo = nameStore();
-```
-
-But it's not enough. Because we can create two instances of `nameStore`, and they will have the same `sid`-s. So, plugin will wrap `nameStore` with `withFactory` helper:
-
-```ts
-function nameStore() {
- const $name = createStore(null, { sid: 'ffds2' });
-
- return { $name };
-}
-
-const personOne = withFactory({
- sid: 'gre24f',
- fn: () => nameStore(),
-});
-const personTwo = withFactory({
- sid: 'lpefgd',
- fn: () => nameStore(),
-});
-```
-
-Now, `sid`-s of inner units are unique, and we can serialize and deserialize them.
-
-```ts
-personOne.$name.sid; // gre24f|ffds2
-personTwo.$name.sid; // lpefgd|ffds2
-```
-
-### How `withFactory` works
-
-`withFactory` is a helper that allows to create unique `sid`-s for inner units. It is a function that accepts an object with `sid` and `fn` properties. `sid` is a unique identifier of the factory, and `fn` is a function that creates units.
-
-Internal implementation of `withFactory` is pretty simple, it puts received `sid` to the global scope before `fn` call, and removes it after. Any Effector's creator function tries to read this global value while creating and append its value to the `sid` of the unit.
-
-```ts
-let globalSid = null;
-
-function withFactory({ sid, fn }) {
- globalSid = sid;
-
- const result = fn();
-
- globalSid = null;
-
- return result;
-}
-
-function createStore(initialValue, { sid }) {
- if (globalSid) {
- sid = `${globalSid}|${sid}`;
- }
-
- // ...
-}
-```
-
-Because of single thread nature of JavaScript, it is safe to use global variables for this purpose.
-
-:::info
-Of course, the real implementation is a bit more complicated, but the idea is the same.
-:::
-
-## Summary
-
-1. Any multi-store state manager requires unique identifiers for every store to distinguish them between different environments.
-2. In Effector's world this kind of strings are called `sid`.
-3. Plugins for code transformations add `sid`-s and meta-information to raw Effector's units creation, like `createStore` or `createEvent`.
-4. Plugins for code transformations wrap custom factories with `withFactory` helper that allow to make `sid`-s of inner units unique as well.
+Article is moved to [official documentation of Effector](https://effector.dev/en/explanation/sids/).
diff --git a/apps/website/docs/recipes/ssr.md b/apps/website/docs/recipes/ssr.md
index f61ef01dc..77a6449c7 100644
--- a/apps/website/docs/recipes/ssr.md
+++ b/apps/website/docs/recipes/ssr.md
@@ -5,7 +5,7 @@ One of the most important and difficult to implement part of SSR is data-fetchin
Farfetched is based on [Effector](https://effector.dev), that have an [excellent support of SSR](https://dev.to/effector/the-best-part-of-effector-4c27), so you can handle data-fetching easily if you follow some simple rules:
- [**do not** start fetching in render-cycle](/statements/render_as_you_fetch.md)
-- **do** use [Fork API in Effector](https://effector.dev/en/api/effector/fork/) and make sure that your application has correct [SIDs](/recipes/sids)
+- **do** use [Fork API in Effector](https://effector.dev/en/api/effector/fork/) and make sure that your application has correct [SIDs](https://effector.dev/en/explanation/sids/)
- **do** use [Effector](https://effector.dev) operators to express your control flow
That is it, just start your application on server and wait for all computation finished:
diff --git a/apps/website/docs/recipes/testing.md b/apps/website/docs/recipes/testing.md
index fd9d200b1..94172d08f 100644
--- a/apps/website/docs/recipes/testing.md
+++ b/apps/website/docs/recipes/testing.md
@@ -1,7 +1,7 @@
# Unit tests
::: info
-For better testing experience, we recommend reading article about [SIDs](/recipes/sids)
+For better testing experience, we recommend reading article about [SIDs](https://effector.dev/en/explanation/sids/)
:::
Farfetched offers a couple of features to simplify writing unit tests.
diff --git a/apps/website/docs/recipes/vite.md b/apps/website/docs/recipes/vite.md
index bcb9e9fed..fe86a525f 100644
--- a/apps/website/docs/recipes/vite.md
+++ b/apps/website/docs/recipes/vite.md
@@ -1,7 +1,7 @@
# Vite
:::info
-Farfetched does not require any special configuration for Vite for basic usage. However, if you want to use advanced features like [`cache`](/api/operators/cache) or [server-side rendering](/recipes/ssr), you need to configure Vite. Detailed explanation of the reasons is available in [deep-dive article](/recipes/sids).
+Farfetched does not require any special configuration for Vite for basic usage. However, if you want to use advanced features like [`cache`](/api/operators/cache) or [server-side rendering](/recipes/ssr), you need to configure Vite. Detailed explanation of the reasons is available in [deep-dive article](https://effector.dev/en/explanation/sids/).
:::
[Vite](https://vitejs.dev/) uses ESBuild under the hood, which does not allow to use its internal AST in the plugins. To apply custom transformations to the code one must use either [Babel](https://github.com/owlsdepartment/vite-plugin-babel) or [SWC](https://github.com/egoist/unplugin-swc), which are allowing custom AST-transformations.
@@ -80,60 +80,7 @@ export default defineConfig({
Note that [plugins for SWC are experimental](https://github.com/swc-project/swc/discussions/3540) and may not work as expected. We recommend to stick with Babel for now.
:::
-1. Install required dependencies:
-
-::: code-group
-
-```sh [pnpm]
-pnpm add --save-dev unplugin-swc effector-swc-plugin @swc/core
-```
-
-```sh [yarn]
-yarn add --dev unplugin-swc effector-swc-plugin @swc/core
-```
-
-```sh [npm]
-npm install --dev unplugin-swc effector-swc-plugin @swc/core
-```
-
-:::
-
-2. Add [`unplugin-swc`](https://github.com/egoist/unplugin-swc) and [`effector-swc-plugin`](https://github.com/kireevmp/effector-swc-plugin) to your config:
-
-```ts
-// vite.config.ts
-import { defineConfig } from 'vite';
-import swc from 'unplugin-swc';
-
-export default defineConfig({
- plugins: [
- swc.vite({
- jsc: {
- experimental: {
- plugins: ['effector-swc-plugin'],
- },
- },
- }),
- ],
-});
-```
-
-::: tip
-If you are using [`@vitejs/plugin-react-swc`](https://github.com/vitejs/vite-plugin-react-swc) in your project, you do not need to add `unplugin-swc` to your config, because it is already included in `@vitejs/plugin-react-swc`. So, just modify your config to enable `effector-swc-plugin`.
-
-```ts
-// vite.config.js
-import { defineConfig } from 'vite';
-import react from "@vitejs/plugin-react-swc";
-
-export default defineConfig({
- plugins: [
- react({ plugins: [["effector-swc-plugin", {}]] });
- ],
-});
-```
-
-:::
+Due to the experimental status of SWC plugins, we do not provide a detailed guide on how to use SWC with Farfetched. However, you can find an instruction in the official documentation of [`@effector/swc-plugin`](https://effector.dev/en/api/effector/swc-plugin/).
## Disable HMR
diff --git a/apps/website/docs/releases/canary.md b/apps/website/docs/releases/canary.md
index 27b820e86..a58bf9253 100644
--- a/apps/website/docs/releases/canary.md
+++ b/apps/website/docs/releases/canary.md
@@ -2,90 +2,4 @@
sidebar: false
---
-# Canary versions of Farfetched
-
-:::danger
-Canary versions are not intended for production use. They can contain bugs and breaking changes, some features can be removed or changed in the stable release.
-:::
-
-We release canary versions of Farfetched to allow you to try new features before they are released. Canary versions are published for every PR that contains changesets. You can find the latest canary version of the package for particular PR in the PR comments.
-
-## How to use
-
-1. Replace current versions with the canary versions in `package.json`
-
-```json
-{
- "dependencies": {
- "@farfetched/core": "0.10.4", // [!code --]
- "@farfetched/core": "npm:@farfetched-canary/core@0.10.7-403.0" // [!code ++]
- }
-}
-```
-
-2. Install packages
-
-::: code-group
-
-```bash [pnpm]
-pnpm install
-```
-
-```bash [yarn]
-yarn install
-```
-
-```bash [npm]
-npm install
-```
-
-3. Test your application with the canary version of Farfetched
-
-:::
-
-## Deep-dive
-
-In this section, you can find more details about canary versions publishing process.
-
-### Package names
-
-Canary versions of Farfetched are published to scope `@farfetched-canary` instead of `@farfetched`. To use them, you need to change the package name in `package.json` from `@farfetched/*` to `@farfetched-canary/*`.
-
-::: details Full mapping
-
-
-
-
-
-
- Release package name |
- Canary package name |
-
-
-
-
- {{item.release}} |
- {{item.canary}} |
-
-
-
-
-:::
-
-### Package versions
-
-Package versions for canary versions of Farfetched are generated automatically by the following rules:
-
-1. Generate next version of the package according to [semver](https://semver.org/) rules based on changesets in the branch.
-2. Add PR number to the end of the version.
-3. Add build number to the end of the version.
-
-::: details Examples
-
-- If the latest version of the package is `0.10.4` and branch contains changeset for `minor` change, PR number is `403` and this is the first build for this PR, then the version of the package will be `0.11.0-403.0`.
-
-- If the latest version of the package is `0.10.4` and branch contains changeset for `patch` change, PR number is `406` and this is the second build for this PR, then the version of the package will be `0.10.5-406.1`.
-
-:::
+Canary version is not available anymore.
diff --git a/apps/website/docs/releases/canary_mapping.data.ts b/apps/website/docs/releases/canary_mapping.data.ts
deleted file mode 100644
index d4560200c..000000000
--- a/apps/website/docs/releases/canary_mapping.data.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { readdir, readFile, stat } from 'node:fs/promises';
-import * as path from 'node:path';
-
-export default {
- async load() {
- const PACKAGES_PATH = '../../packages';
-
- const inDirList = await readdir(PACKAGES_PATH);
-
- const packageNames: string[] = [];
-
- await Promise.all(
- inDirList.map(async (dir) => {
- const stats = await stat(`${PACKAGES_PATH}/${dir}`);
- if (!stats.isDirectory()) {
- return;
- }
-
- const packageJson = await readFile(
- path.join(PACKAGES_PATH, dir, 'package.json'),
- 'utf-8'
- ).then(JSON.parse);
-
- packageNames.push(packageJson.name);
- })
- );
-
- return packageNames.map((packageName) => ({
- release: packageName,
- canary: packageName.replace('@farfetched', '@farfetched-canary'),
- }));
- },
-};
diff --git a/apps/website/docs/releases/index.md b/apps/website/docs/releases/index.md
index d30a358f5..2df4f5ad7 100644
--- a/apps/website/docs/releases/index.md
+++ b/apps/website/docs/releases/index.md
@@ -6,10 +6,6 @@ sidebar: false
Farfetched is mostly been creating in Thailand, so all releases are named after beautiful places in Thailand.
-:::tip
-To use unreleased version of Farfetched, please refer to [canary](/releases/canary) page.
-:::
-
diff --git a/apps/website/docs/shared/sids_plugins.md b/apps/website/docs/shared/sids_plugins.md
index dcda5e49b..3bbeff26e 100644
--- a/apps/website/docs/shared/sids_plugins.md
+++ b/apps/website/docs/shared/sids_plugins.md
@@ -18,40 +18,7 @@ Read more about `effector/babel-plugin` configuration in the [Effector's documen
Note that [plugins for SWC are experimental](https://github.com/swc-project/swc/discussions/3540) and may not work as expected. We recommend to stick with Babel for now.
:::
-[SWC](https://swc.rs) is a blazing fast alternative to Babel. If you are using it, you can install `effector-swc-plugin` to get the same DX as with Babel.
-
-::: code-group
-
-```sh [pnpm]
-pnpm add --save-dev effector-swc-plugin @swc/core
-```
-
-```sh [yarn]
-yarn add --dev effector-swc-plugin @swc/core
-```
-
-```sh [npm]
-npm install --dev effector-swc-plugin @swc/core
-```
-
-:::
-
-Now just modify your `.swcrc` config to enable installed plugin:
-
-```json
-{
- "$schema": "https://json.schemastore.org/swcrc",
- "jsc": {
- "experimental": {
- "plugins": ["effector-swc-plugin"]
- }
- }
-}
-```
-
-:::info
-Read more about `effector-swc-plugin` configuration in the [plugin documentation](https://github.com/kireevmp/effector-swc-plugin).
-:::
+If you are using [SWC](https://swc.rs), please read the official documentation of [`@effector/swc-plugin`](https://effector.dev/en/api/effector/swc-plugin/).
**Vite**
diff --git a/apps/website/docs/statements/typescript.md b/apps/website/docs/statements/typescript.md
index 55e68fc71..eb66bd962 100644
--- a/apps/website/docs/statements/typescript.md
+++ b/apps/website/docs/statements/typescript.md
@@ -1,3 +1,15 @@
+---
+outline: [2, 3]
+---
+
# TypeScript
Farfetched is going to provide first-class support of TypeScript types. It is written in TypeScript, and it has a lot of type-tests. However, TypeScript itself does not aim for [apply a sound or "provably correct" type system](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals), instead it strikes a balance between correctness and productivity. So, we cannot guarantee that all the types are correct, but we are going to do our best to provide the best possible types.
+
+## Known issues
+
+TS itself has some limitations, and Farfetched is not an exception, we cannot fix this issues, but we can provide some workarounds. Here is a list of known issues:
+
+### `declareParams`
+
+It is recommended to use `type` instead of `interface` in `declareParams`, because `interface` can break the type inference in [some cases](https://github.com/igorkamyshev/farfetched/issues/266). The exhaustive reasons of the issue could be found in the [answer on StackOverflow](https://stackoverflow.com/questions/55814516/typescript-why-type-alias-satisfies-a-constraint-but-same-interface-doesnt).
diff --git a/apps/website/docs/tutorial/concurrency.md b/apps/website/docs/tutorial/concurrency.md
index 6e25c3cc4..574955b95 100644
--- a/apps/website/docs/tutorial/concurrency.md
+++ b/apps/website/docs/tutorial/concurrency.md
@@ -161,6 +161,36 @@ const query = createQuery({
query.aborted // will be called when the operation is cancelled
```
+## Mutations
+
+::: danger TL;DR
+[`concurrency`](/api/operators/concurrency) supports [_Mutations_](/api/primitives/mutation) as well. However, it is not recommended to use it with [_Mutations_](/api/primitives/mutation) because of its the nature — they are not idempotent, and it is hard to predict the outcome of the operation if it is cancelled.
+:::
+
+Let us say we have a [_Mutation_](/api/primitives/mutation) that posts a new comment to the server:
+
+```ts
+import { createJsonMutation, declareParams } from '@farfetched/core';
+
+const postCommentMutation = createJsonMutation({
+ params: declareParams<{ text: string }>(),
+ request: {
+ url: '/comments',
+ method: 'POST',
+ },
+});
+```
+
+We might want to cancel in flight comment posting if the user decides to post another comment. We can use the `concurrency` operator to achieve this:
+
+```ts
+import { concurrency } from '@farfetched/core';
+
+concurrency(postCommentMutation, { strategy: 'TAKE_LATEST' });
+```
+
+But it could be potentially dangerous because the server might process the first comment even if it was cancelled. So, to avoid such situations it is important to ensure that the server supports [idempotent operations](https://en.wikipedia.org/wiki/Idempotence), communicate with your backend-team to add support for it.
+
## References
- [API Reference: operator `concurrency`](/api/operators/concurrency)
diff --git a/apps/website/docs/tutorial/install.md b/apps/website/docs/tutorial/install.md
index 45e679f03..28c0ffc98 100644
--- a/apps/website/docs/tutorial/install.md
+++ b/apps/website/docs/tutorial/install.md
@@ -45,4 +45,4 @@ For some advanced usage, like [`cache`](/api/operators/cache) or [server-side re
### Deep dive
-If you are interested in how code transformations works under the hood and why they are required for some use cases, you can dive into [advanced article about SIDs](/recipes/sids).
+If you are interested in how code transformations works under the hood and why they are required for some use cases, you can dive into [advanced article about SIDs](https://effector.dev/en/explanation/sids/).
diff --git a/apps/website/docs/tutorial/retries.md b/apps/website/docs/tutorial/retries.md
index 7059adc20..bbf251506 100644
--- a/apps/website/docs/tutorial/retries.md
+++ b/apps/website/docs/tutorial/retries.md
@@ -32,7 +32,7 @@ retry(characterQuery, {
This code works is pretty straightforward, after first failure of `characterQuery`, it calls it again after 500ms. If it fails again, it will call it again after 500ms and so on up yo 5 times. If it succeeded, it will stop retrying.
::: tip
-As soon as Farfetched is [based on Effector](/statements/effector), almost every field of its configs could be static or reactive. So, you can pass a [_Store_](https://effector.dev/en/api/effector/store/) with a number of retires to `times` option as well.
+Since Farfetched is [based on Effector](/statements/effector), almost every field in its configuration can be either static or reactive. For example, you can pass a [_Store_](https://effector.dev/en/api/effector/store/) containing the number of retries to the `times` option.
:::
## Filter retries
diff --git a/packages/atomic-router/CHANGELOG.md b/packages/atomic-router/CHANGELOG.md
index f15cc3bc3..8f14682ef 100644
--- a/packages/atomic-router/CHANGELOG.md
+++ b/packages/atomic-router/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/atomic-router
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/atomic-router/package.json b/packages/atomic-router/package.json
index d09c46f25..a0fdb01c3 100644
--- a/packages/atomic-router/package.json
+++ b/packages/atomic-router/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/atomic-router",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md
index 2824dd2a6..9c22e5353 100644
--- a/packages/core/CHANGELOG.md
+++ b/packages/core/CHANGELOG.md
@@ -1,5 +1,26 @@
# @farfetched/core
+## 0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- 88b6096: Decrease bundle size and key length in `cache` operator by replacing sha-1 by custom hashing function
+- 1d05aba: Fix name extraction in _Query_ and _Mutation_ from babel-plugin/swc-plugin
+
+## 0.12.6
+
+### Patch Changes
+
+- 6107570: Fix types in `connectQuery` in case of source _Query_ with `initialData`
+
+## 0.12.5
+
+### Patch Changes
+
+- 0d4c1a6: Fix support of relative urls in `createJsonQuery` and `createJsonMutation`
+
## 0.12.4
## 0.12.3
diff --git a/packages/core/package.json b/packages/core/package.json
index 1e3d1c113..154db19ad 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/core",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
@@ -41,7 +41,7 @@
"size-limit": [
{
"path": "./dist/core.js",
- "limit": "16.44 kB"
+ "limit": "15.52 kB"
}
]
}
diff --git a/packages/core/src/__tests__/relative_urls_in_jsdom.test.ts b/packages/core/src/__tests__/relative_urls_in_jsdom.test.ts
new file mode 100644
index 000000000..ac82c6135
--- /dev/null
+++ b/packages/core/src/__tests__/relative_urls_in_jsdom.test.ts
@@ -0,0 +1,54 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { describe, test, expect } from 'vitest';
+import { allSettled, fork } from 'effector';
+
+import { createJsonQuery } from '../query/create_json_query';
+import { unknownContract } from '../contract/unknown_contract';
+import { fetchFx } from '../fetch/fetch';
+
+describe('relative paths in createJsonQuery, issue #493', () => {
+ test('does not throw error for valid relative path', async () => {
+ const query = createJsonQuery({
+ request: { url: '/api', method: 'GET' },
+ response: { contract: unknownContract },
+ });
+
+ const scope = fork({
+ // We have to to mock fetchFx, because URL validation embed in createJsonQuery.__.executeFx
+ handlers: [[fetchFx, () => new Response(JSON.stringify('DATA'))]],
+ });
+
+ await allSettled(query.start, { scope });
+
+ expect(scope.getState(query.$error)).toBe(null);
+ expect(scope.getState(query.$data)).toBe('DATA');
+ });
+
+ test('does throw error for invalid relative path', async () => {
+ const query = createJsonQuery({
+ request: { url: 'api **** jkjj', method: 'GET' },
+ response: { contract: unknownContract },
+ });
+
+ const scope = fork({
+ // We have to to mock fetchFx, because URL validation embed in createJsonQuery.__.executeFx
+ handlers: [[fetchFx, () => new Response(JSON.stringify('DATA'))]],
+ });
+
+ await allSettled(query.start, { scope });
+
+ expect(scope.getState(query.$error)).toMatchInlineSnapshot(`
+ {
+ "errorType": "CONFIGURATION",
+ "explanation": "Operation is misconfigured",
+ "reason": "Invalid URL",
+ "validationErrors": [
+ ""api **** jkjj" is not valid URL",
+ ],
+ }
+ `);
+ expect(scope.getState(query.$data)).toBe(null);
+ });
+});
diff --git a/packages/core/src/cache/__test__/cache.test.ts b/packages/core/src/cache/__test__/cache.test.ts
index a3b02d700..b861a092d 100644
--- a/packages/core/src/cache/__test__/cache.test.ts
+++ b/packages/core/src/cache/__test__/cache.test.ts
@@ -8,7 +8,7 @@ import { Contract } from '../../contract/type';
import { createQuery } from '../../query/create_query';
import { inMemoryCache } from '../adapters/in_memory';
import { cache } from '../cache';
-import { sha1 } from '../lib/hash';
+import { hashCode } from '../lib/hash';
import { createJsonQuery } from '../../query/create_json_query';
import { declareParams } from '../../remote_operation/params';
import { unknownContract } from '../../contract/unknown_contract';
@@ -144,7 +144,7 @@ describe('cache', () => {
await allSettled(adapter.set, {
scope,
params: {
- key: sha1(
+ key: hashCode(
query.$data.sid +
/* params is undefined */ JSON.stringify(undefined) +
/* sources is [] */ JSON.stringify([])
diff --git a/packages/core/src/cache/key/key.ts b/packages/core/src/cache/key/key.ts
index d868d2a65..2f933d425 100644
--- a/packages/core/src/cache/key/key.ts
+++ b/packages/core/src/cache/key/key.ts
@@ -1,5 +1,5 @@
import { Query } from '../../query/type';
-import { sha1 } from '../lib/hash';
+import { hashCode } from '../lib/hash';
import { stableStringify } from '../lib/stable_stringify';
export function createHumanReadbleKey({
@@ -30,7 +30,7 @@ export function createKey({
try {
const stableString = stableStringify({ params, sources, sid })!;
- return sha1(stableString);
+ return hashCode(stableString);
} catch (e: unknown) {
return null;
}
@@ -50,7 +50,7 @@ export function queryUniqId(query: Query) {
}
throw new Error(
- 'Query does not have sid or uniq name, which is required for caching, read more https://ff.effector.dev/recipes/sids.html'
+ 'Query does not have sid or uniq name, which is required for caching, read more https://effector.dev/en/explanation/sids/'
);
}
diff --git a/packages/core/src/cache/lib/__test__/hash.test.ts b/packages/core/src/cache/lib/__test__/hash.test.ts
index 726ce90cd..acaafbb99 100644
--- a/packages/core/src/cache/lib/__test__/hash.test.ts
+++ b/packages/core/src/cache/lib/__test__/hash.test.ts
@@ -1,54 +1,41 @@
import { describe, test, expect } from 'vitest';
-import { sha1 } from '../hash';
+import { hashCode } from '../hash';
-// Tests is copied from https://github.com/emn178/js-sha1/blob/master/tests/test.js
-describe('sha1', () => {
+describe('hashCode', () => {
test.each([
- ['', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
- [
- 'The quick brown fox jumps over the lazy dog',
- '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12',
- ],
- [
- 'The quick brown fox jumps over the lazy dog.',
- '408d94384216f890ff7a0c3528e8bed1e0b01621',
- ],
+ ['', '0'],
+ ['The quick brown fox jumps over the lazy dog', '-a2u5rh'],
+ ['The quick brown fox jumps over the lazy dog.', '-sbiqpx'],
[
'The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications, and is also commonly used to verify data integrity.',
- '8690faab7755408a03875895176fac318f14a699',
+ 'eamfrc',
],
- ['中文', '7be2d2d20c106eee0836c9bc2b939890a78e8fb3'],
- ['aécio', '9e4e5d978deced901d621475b03f1ded19e945bf'],
+ ['中文', 'dure'],
+ ['aécio', '1lixi9'],
[
'訊息摘要演算法第五版(英語:Message-Digest Algorithm 5,縮寫為MD5),是當前電腦領域用於確保資訊傳輸完整一致而廣泛使用的雜湊演算法之一',
- 'ad8aae581c915fe01c4964a5e8b322cae74ee5c5',
+ '-w5hlrk',
],
[
'訊息摘要演算法第五版(英語:Message-Digest Algorithm 5,縮寫為MD5),是當前電腦領域用於確保資訊傳輸完整一致而廣泛使用的雜湊演算法之一(又譯雜湊演算法、摘要演算法等),主流程式語言普遍已有MD5的實作。',
- '3a15ad3ce9efdd4bf982eaaaecdeda36a887a3f9',
- ],
- [
- '0123456780123456780123456780123456780123456780123456780',
- '4cdeae78e8b7285aef73e0a15eec7d5b30f3f3e3',
- ],
- [
- '01234567801234567801234567801234567801234567801234567801',
- 'e657e6bb6b5d0c2bf7e929451c14a5302589a60b',
+ '-bdhbwb',
],
+ ['0123456780123456780123456780123456780123456780123456780', 'ju78hc'],
+ ['01234567801234567801234567801234567801234567801234567801', '-o9s6tb'],
[
'0123456780123456780123456780123456780123456780123456780123456780',
- 'e7ad97591c1a99d54d80751d341899769884c75a',
+ 'vbp3lo',
],
[
'01234567801234567801234567801234567801234567801234567801234567801234567',
- '55a13698cdc010c0d16dab2f7dc10f43a713f12f',
+ '-qz9yo8',
],
[
'012345678012345678012345678012345678012345678012345678012345678012345678',
- '006575418c27b0158e55a6d261c46f86b33a496a',
+ 'fzrsw0',
],
])('"%s" -> "%s"', (source, hash) => {
- expect(sha1(source)).toEqual(hash);
+ expect(hashCode(source)).toEqual(hash);
});
});
diff --git a/packages/core/src/cache/lib/hash.ts b/packages/core/src/cache/lib/hash.ts
index 27bc9bb02..4d773f045 100644
--- a/packages/core/src/cache/lib/hash.ts
+++ b/packages/core/src/cache/lib/hash.ts
@@ -1,157 +1,6 @@
-// Copied from http://www.movable-type.co.uk/scripts/sha1.html
-
-/**
- * Generates SHA-1 hash of string
- */
-export function sha1(source: string): string {
- // convert string to UTF-8, as SHA only deals with byte-streams
- let msg = encodeUTF8(source);
-
- // constants [§4.2.1]
- const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
-
- // PREPROCESSING
- msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
-
- // convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
- const l = msg.length / 4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
- const N = Math.ceil(l / 16); // number of 16-integer-blocks required to hold 'l' ints
- const M = new Array(N);
-
- for (let i = 0; i < N; i++) {
- M[i] = new Array(16);
- for (let j = 0; j < 16; j++) {
- // encode 4 chars per integer, big-endian encoding
- M[i][j] =
- (msg.charCodeAt(i * 64 + j * 4) << 24) |
- (msg.charCodeAt(i * 64 + j * 4 + 1) << 16) |
- (msg.charCodeAt(i * 64 + j * 4 + 2) << 8) |
- msg.charCodeAt(i * 64 + j * 4 + 3);
- } // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
- }
- // add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
- // note: most significant word would be (len-1)*8 >>> 32, but since JS converts
- // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
- M[N - 1][14] = ((msg.length - 1) * 8) / Math.pow(2, 32);
- M[N - 1][14] = Math.floor(M[N - 1][14]);
- M[N - 1][15] = ((msg.length - 1) * 8) & 0xffffffff;
-
- // set initial hash value [§5.3.1]
- let H0 = 0x67452301;
- let H1 = 0xefcdab89;
- let H2 = 0x98badcfe;
- let H3 = 0x10325476;
- let H4 = 0xc3d2e1f0;
-
- // HASH COMPUTATION [§6.1.2]
-
- const W = new Array(80);
- let a: number, b: number, c: number, d: number, e: number;
- for (let i = 0; i < N; i++) {
- // 1 - prepare message schedule 'W'
- for (let t = 0; t < 16; t++) W[t] = M[i][t];
- for (let t = 16; t < 80; t++)
- W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
-
- // 2 - initialise five working variables a, b, c, d, e with previous hash value
- a = H0;
- b = H1;
- c = H2;
- d = H3;
- e = H4;
-
- // 3 - main loop
- for (let t = 0; t < 80; t++) {
- // seq for blocks of 'f' functions and 'K' constants
- const s = Math.floor(t / 20) as 0 | 1 | 2 | 3; // it is safe to use 0 | 1 | 2 | 3 because of max value of t is 79
- const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) & 0xffffffff;
- e = d;
- d = c;
- c = ROTL(b, 30);
- b = a;
- a = T;
- }
-
- // 4 - compute the new intermediate hash value
- H0 = (H0 + a) & 0xffffffff; // note 'addition modulo 2^32'
- H1 = (H1 + b) & 0xffffffff;
- H2 = (H2 + c) & 0xffffffff;
- H3 = (H3 + d) & 0xffffffff;
- H4 = (H4 + e) & 0xffffffff;
- }
-
- return (
- toHexString(H0) +
- toHexString(H1) +
- toHexString(H2) +
- toHexString(H3) +
- toHexString(H4)
- );
-}
-
-//
-// function 'f' [§4.1.1]
-//
-function f(s: 0 | 1 | 2 | 3, x: number, y: number, z: number): number {
- switch (s) {
- case 0:
- return (x & y) ^ (~x & z); // Ch()
- case 1:
- return x ^ y ^ z; // Parity()
- case 2:
- return (x & y) ^ (x & z) ^ (y & z); // Maj()
- case 3:
- return x ^ y ^ z; // Parity()
- }
-}
-
-/**
- * rotate left (circular left shift) value x by n positions [§3.2.5]
- */
-function ROTL(x: number, n: number) {
- return (x << n) | (x >>> (32 - n));
-}
-
-/**
- * hexadecimal representation of a number
- */
-function toHexString(n: number): string {
- let s = '';
- let v;
- for (let i = 7; i >= 0; i--) {
- v = (n >>> (i * 4)) & 0xf;
- s += v.toString(16);
- }
- return s;
-}
-
-/**
- * Encode multi-byte Unicode string into utf-8 multiple single-byte characters
- * (BMP / basic multilingual plane only)
- *
- * Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
- *
- * @param {String} unicodeString Unicode string to be encoded as UTF-8
- * @returns {String} encoded string
- */
-function encodeUTF8(unicodeString: string): string {
- return unicodeString
- .replace(
- /[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
- (c) => {
- const cc = c.charCodeAt(0);
- return String.fromCharCode(0xc0 | (cc >> 6), 0x80 | (cc & 0x3f));
- }
- )
- .replace(
- /[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
- function (c) {
- const cc = c.charCodeAt(0);
- return String.fromCharCode(
- 0xe0 | (cc >> 12),
- 0x80 | ((cc >> 6) & 0x3f),
- 0x80 | (cc & 0x3f)
- );
- }
- );
+export function hashCode(s: string) {
+ let h = 0;
+ let i = 0;
+ while (i < s.length) h = ((h << 5) - h + s.charCodeAt(i++)) | 0;
+ return h.toString(36);
}
diff --git a/packages/core/src/fetch/lib.ts b/packages/core/src/fetch/lib.ts
index a6d87d3f8..f2c5a9b56 100644
--- a/packages/core/src/fetch/lib.ts
+++ b/packages/core/src/fetch/lib.ts
@@ -73,6 +73,11 @@ export function formatUrl(
url: string,
queryRecord: FetchApiRecord | string
): URL {
+ let urlBase: string | undefined;
+ if (url.startsWith('/')) {
+ urlBase = window.location.origin;
+ }
+
let urlString: string;
let queryString: string;
@@ -89,7 +94,7 @@ export function formatUrl(
}
try {
- return new URL(urlString);
+ return new URL(urlString, urlBase);
} catch (e) {
throw configurationError({
reason: 'Invalid URL',
diff --git a/packages/core/src/libs/patronus/factory_name.ts b/packages/core/src/libs/patronus/factory_name.ts
new file mode 100644
index 000000000..cb7baf90e
--- /dev/null
+++ b/packages/core/src/libs/patronus/factory_name.ts
@@ -0,0 +1,7 @@
+import { createNode } from 'effector';
+
+export function getFactoryName(): string | undefined {
+ return (
+ createNode({ regional: true }).family.owners[0]?.meta?.name ?? undefined
+ );
+}
diff --git a/packages/core/src/libs/patronus/index.ts b/packages/core/src/libs/patronus/index.ts
index ebc9dfd35..4a6c41cec 100644
--- a/packages/core/src/libs/patronus/index.ts
+++ b/packages/core/src/libs/patronus/index.ts
@@ -20,3 +20,4 @@ export { and } from './and';
export { readonly } from './readonly';
export { syncBatch } from './sync_batch';
export { combineEvents } from './combine_events';
+export { getFactoryName } from './factory_name';
diff --git a/packages/core/src/mutation/__tests__/create_mutation.test.ts b/packages/core/src/mutation/__tests__/create_mutation.test.ts
index 897fcc658..c18202fd8 100644
--- a/packages/core/src/mutation/__tests__/create_mutation.test.ts
+++ b/packages/core/src/mutation/__tests__/create_mutation.test.ts
@@ -3,6 +3,7 @@ import { describe, test, expect, vi } from 'vitest';
import { watchRemoteOperation } from '../../test_utils/watch_query';
import { createMutation } from '../create_mutation';
+import { withFactory } from '../../libs/patronus';
describe('createMutation', () => {
test('use function as handler', async () => {
@@ -96,4 +97,17 @@ describe('createMutation', () => {
expect(handler).not.toBeCalled();
});
+
+ test('get name from factory', () => {
+ const q = withFactory({
+ name: 'myMutationName',
+ sid: 'q',
+ fn: () =>
+ createMutation({
+ handler: async (_: void) => {},
+ }),
+ });
+
+ expect(q.__.meta.name).toBe('myMutationName');
+ });
});
diff --git a/packages/core/src/mutation/create_headless_mutation.ts b/packages/core/src/mutation/create_headless_mutation.ts
index 9903a3026..cd843ed16 100644
--- a/packages/core/src/mutation/create_headless_mutation.ts
+++ b/packages/core/src/mutation/create_headless_mutation.ts
@@ -5,6 +5,7 @@ import {
readonly,
type DynamicallySourcedField,
type StaticOrReactive,
+ getFactoryName,
} from '../libs/patronus';
import { type Mutation, MutationSymbol } from './type';
import { type Contract } from '../contract/type';
@@ -48,7 +49,7 @@ export function createHeadlessMutation<
MapDataSource,
ValidationSource
>({
- name,
+ name: name ?? getFactoryName(),
serialize: 'ignore',
enabled,
kind: MutationSymbol,
diff --git a/packages/core/src/query/__tests__/connect_query.test-d.ts b/packages/core/src/query/__tests__/connect_query.test-d.ts
index edf88c393..aaa6bcd8c 100644
--- a/packages/core/src/query/__tests__/connect_query.test-d.ts
+++ b/packages/core/src/query/__tests__/connect_query.test-d.ts
@@ -226,4 +226,33 @@ describe('connectQuery', () => {
target: query2,
});
});
+
+ test('allows query with initialData to be used as source', () => {
+ const query1 = createQuery({
+ initialData: [],
+ async handler(ids: number[]) {
+ return Promise.resolve([1]);
+ },
+ });
+
+ const query2 = createQuery({
+ initialData: [],
+ async handler(ids: number[]) {
+ return Promise.resolve([1]);
+ },
+ });
+
+ connectQuery({
+ source: query1,
+ fn: (a) => {
+ a.params.forEach;
+ a.result.forEach;
+
+ return {
+ params: [1],
+ };
+ },
+ target: query2,
+ });
+ });
});
diff --git a/packages/core/src/query/__tests__/create_query.test.ts b/packages/core/src/query/__tests__/create_query.test.ts
index c6ab80197..ad533dfd1 100644
--- a/packages/core/src/query/__tests__/create_query.test.ts
+++ b/packages/core/src/query/__tests__/create_query.test.ts
@@ -4,6 +4,7 @@ import { describe, test, expect, vi } from 'vitest';
import { createQuery } from '../create_query';
import { onAbort } from '../../remote_operation/on_abort';
import { createDefer } from '../../libs/lohyphen';
+import { withFactory } from '../../libs/patronus';
import { setTimeout } from 'timers/promises';
describe('core/createQuery/handler', () => {
@@ -164,4 +165,17 @@ describe('createQuery/onAbort', () => {
expect(scope.getState(q.$status)).toBe('initial');
expect(abortListener).toHaveBeenCalledTimes(1);
});
+
+ test('get name from factory', () => {
+ const q = withFactory({
+ name: 'myQueryName',
+ sid: 'q',
+ fn: () =>
+ createQuery({
+ handler: async (_: void) => {},
+ }),
+ });
+
+ expect(q.__.meta.name).toBe('myQueryName');
+ });
});
diff --git a/packages/core/src/query/connect_query.ts b/packages/core/src/query/connect_query.ts
index 8308f396a..1ee98bce3 100644
--- a/packages/core/src/query/connect_query.ts
+++ b/packages/core/src/query/connect_query.ts
@@ -19,7 +19,7 @@ export function connectQuery>(
} & (Target extends Query
? P extends void
? { fn?: undefined; filter?: () => boolean }
- : Sources extends Query
+ : Sources extends Query
? {
fn: (sources: {
result: RemoteOperationResult;
@@ -32,7 +32,7 @@ export function connectQuery>(
params: RemoteOperationParams;
}) => boolean;
}
- : Sources extends Record>
+ : Sources extends Record>
? {
fn: (sources: {
[index in keyof Sources]: {
diff --git a/packages/core/src/query/create_headless_query.ts b/packages/core/src/query/create_headless_query.ts
index f11cb2687..f6ed74580 100644
--- a/packages/core/src/query/create_headless_query.ts
+++ b/packages/core/src/query/create_headless_query.ts
@@ -19,6 +19,7 @@ import {
type StaticOrReactive,
type DynamicallySourcedField,
type SourcedField,
+ getFactoryName,
} from '../libs/patronus';
import { type Validator } from '../validation/type';
import { type Query, type QueryMeta, QuerySymbol } from './type';
@@ -86,7 +87,7 @@ export function createHeadlessQuery<
MapDataSource,
ValidationSource
>({
- name,
+ name: name ?? getFactoryName(),
kind: QuerySymbol,
serialize: serializationForSideStore(serialize),
enabled,
diff --git a/packages/dev-tools/CHANGELOG.md b/packages/dev-tools/CHANGELOG.md
index d6580d482..2da78fd84 100644
--- a/packages/dev-tools/CHANGELOG.md
+++ b/packages/dev-tools/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/dev-tools
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/dev-tools/package.json b/packages/dev-tools/package.json
index d161f8e1c..9a779761f 100644
--- a/packages/dev-tools/package.json
+++ b/packages/dev-tools/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/dev-tools",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/io-ts/CHANGELOG.md b/packages/io-ts/CHANGELOG.md
index 7b7185b49..2a285eb6b 100644
--- a/packages/io-ts/CHANGELOG.md
+++ b/packages/io-ts/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/io-ts
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/io-ts/package.json b/packages/io-ts/package.json
index 3591a752d..6a081ad03 100644
--- a/packages/io-ts/package.json
+++ b/packages/io-ts/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/io-ts",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/json-schema/CHANGELOG.md b/packages/json-schema/CHANGELOG.md
index 818628e62..388e7907c 100644
--- a/packages/json-schema/CHANGELOG.md
+++ b/packages/json-schema/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/json-schema
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/json-schema/package.json b/packages/json-schema/package.json
index 185557206..792587057 100644
--- a/packages/json-schema/package.json
+++ b/packages/json-schema/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/json-schema",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/runtypes/CHANGELOG.md b/packages/runtypes/CHANGELOG.md
index 55af91950..8ff5f68f8 100644
--- a/packages/runtypes/CHANGELOG.md
+++ b/packages/runtypes/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/runtypes
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/runtypes/package.json b/packages/runtypes/package.json
index 04c975261..da8637ad2 100644
--- a/packages/runtypes/package.json
+++ b/packages/runtypes/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/runtypes",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/solid/CHANGELOG.md b/packages/solid/CHANGELOG.md
index be2e5a5c1..b53a2b5cb 100644
--- a/packages/solid/CHANGELOG.md
+++ b/packages/solid/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/solid
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/solid/package.json b/packages/solid/package.json
index dfbad4900..dbde746c6 100644
--- a/packages/solid/package.json
+++ b/packages/solid/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/solid",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/superstruct/CHANGELOG.md b/packages/superstruct/CHANGELOG.md
index cbbe2cf74..ad23de27f 100644
--- a/packages/superstruct/CHANGELOG.md
+++ b/packages/superstruct/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/superstruct
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/superstruct/package.json b/packages/superstruct/package.json
index 2cdd2ce61..832c3ef1d 100644
--- a/packages/superstruct/package.json
+++ b/packages/superstruct/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/superstruct",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/typed-contracts/CHANGELOG.md b/packages/typed-contracts/CHANGELOG.md
index ea2c05474..e276e952e 100644
--- a/packages/typed-contracts/CHANGELOG.md
+++ b/packages/typed-contracts/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/typed-contracts
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/typed-contracts/package.json b/packages/typed-contracts/package.json
index d93135372..b24b7f6ff 100644
--- a/packages/typed-contracts/package.json
+++ b/packages/typed-contracts/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/typed-contracts",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/valibot/CHANGELOG.md b/packages/valibot/CHANGELOG.md
index bb6eed9c3..b4a463bbd 100644
--- a/packages/valibot/CHANGELOG.md
+++ b/packages/valibot/CHANGELOG.md
@@ -1,5 +1,33 @@
# @farfetched/valibot
+## 0.12.8
+
+### Patch Changes
+
+- @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/valibot/package.json b/packages/valibot/package.json
index 53f40286c..a197a4873 100644
--- a/packages/valibot/package.json
+++ b/packages/valibot/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/valibot",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/zod/CHANGELOG.md b/packages/zod/CHANGELOG.md
index d13cd0c30..590320758 100644
--- a/packages/zod/CHANGELOG.md
+++ b/packages/zod/CHANGELOG.md
@@ -1,5 +1,34 @@
# @farfetched/zod
+## 0.12.8
+
+### Patch Changes
+
+- 7769b64: Fix `zodContracts` type inference for branded types
+ - @farfetched/core@0.12.8
+
+## 0.12.7
+
+### Patch Changes
+
+- Updated dependencies [88b6096]
+- Updated dependencies [1d05aba]
+ - @farfetched/core@0.12.7
+
+## 0.12.6
+
+### Patch Changes
+
+- Updated dependencies [6107570]
+ - @farfetched/core@0.12.6
+
+## 0.12.5
+
+### Patch Changes
+
+- Updated dependencies [0d4c1a6]
+ - @farfetched/core@0.12.5
+
## 0.12.4
### Patch Changes
diff --git a/packages/zod/package.json b/packages/zod/package.json
index b2e066c2a..abdee4977 100644
--- a/packages/zod/package.json
+++ b/packages/zod/package.json
@@ -1,6 +1,6 @@
{
"name": "@farfetched/zod",
- "version": "0.12.4",
+ "version": "0.12.8",
"publishConfig": {
"access": "public"
},
diff --git a/packages/zod/src/__tests__/contract.test-d.ts b/packages/zod/src/__tests__/contract.test-d.ts
index 813e9f937..c9d3b854e 100644
--- a/packages/zod/src/__tests__/contract.test-d.ts
+++ b/packages/zod/src/__tests__/contract.test-d.ts
@@ -58,4 +58,17 @@ describe('zodContract', () => {
>();
}
});
+
+ test('branded type', () => {
+ const BrandedContainer = zod.object({
+ branded: zod.string().brand<'Branded'>(),
+ });
+ const brandedContract = zodContract(BrandedContainer);
+
+ const smth: unknown = { branded: 'branded' };
+
+ if (brandedContract.isData(smth)) {
+ expectTypeOf(smth).toEqualTypeOf>();
+ }
+ });
});
diff --git a/packages/zod/src/zod_contract.ts b/packages/zod/src/zod_contract.ts
index 4006555f3..7e69a9956 100644
--- a/packages/zod/src/zod_contract.ts
+++ b/packages/zod/src/zod_contract.ts
@@ -1,4 +1,4 @@
-import { type ZodType } from 'zod';
+import { type ZodType, type TypeOf } from 'zod';
import { type Contract } from '@farfetched/core';
/**
@@ -7,8 +7,10 @@ import { type Contract } from '@farfetched/core';
*
* @param {ZodType} data Zod Contract for valid data
*/
-function zodContract(data: ZodType): Contract {
- function isData(prepared: unknown): prepared is D {
+function zodContract>(
+ data: T
+): Contract> {
+ function isData(prepared: unknown): prepared is T {
return data.safeParse(prepared).success;
}
diff --git a/tools/scripts/canary/canary_info.mjs b/tools/scripts/canary/canary_info.mjs
deleted file mode 100644
index 40ff1cf8d..000000000
--- a/tools/scripts/canary/canary_info.mjs
+++ /dev/null
@@ -1,22 +0,0 @@
-import { join } from 'node:path';
-import { readFile } from 'node:fs/promises';
-
-import { getPackagesInfo } from '../shared/packages.mjs';
-
-const packages = await getPackagesInfo();
-
-const { root } = packages.at(0);
-const packageJsonPath = join(process.cwd(), root, 'package.json');
-
-const { version: canaryVersion } = await readFile(
- packageJsonPath,
- 'utf-8'
-).then(JSON.parse);
-
-const { changesets: usedChangesets } = await readFile(
- join(process.cwd(), '.changeset', 'pre.json'),
- 'utf-8'
-).then(JSON.parse);
-
-console.log(`canaryVersion="${canaryVersion}"`);
-console.log(`usedChangesets="${JSON.stringify(usedChangesets)}"`);
diff --git a/tools/scripts/canary/canary_name_change.mjs b/tools/scripts/canary/canary_name_change.mjs
deleted file mode 100644
index bbb867911..000000000
--- a/tools/scripts/canary/canary_name_change.mjs
+++ /dev/null
@@ -1,41 +0,0 @@
-import { readFile, writeFile } from 'node:fs/promises';
-import * as path from 'node:path';
-
-import { getPackagesInfo } from '../shared/packages.mjs';
-
-const packages = await getPackagesInfo();
-
-for (const pkg of packages) {
- const packageJsonPath = path.join(process.cwd(), pkg.root, 'package.json');
-
- const originalPackageJson = await readFile(packageJsonPath, 'utf-8').then(
- JSON.parse
- );
-
- const nextPackageJson = {
- ...originalPackageJson,
- name: adjustPackageName(originalPackageJson.name),
- peerDependencies: mapValues(
- originalPackageJson.peerDependencies ?? {},
- (version, name) =>
- name.includes('@farfetched')
- ? `npm:${adjustPackageName(name)}@${originalPackageJson.version}`
- : version
- ),
- };
-
- await writeFile(packageJsonPath, JSON.stringify(nextPackageJson));
-}
-
-function adjustPackageName(name) {
- return name.replaceAll('@farfetched/', '@farfetched-canary/');
-}
-
-export function mapValues(val, fn) {
- const mappedEntries = Object.entries(val).map(([key, value]) => [
- key,
- fn(value, key),
- ]);
-
- return Object.fromEntries(mappedEntries);
-}
diff --git a/tools/scripts/canary/canary_required.mjs b/tools/scripts/canary/canary_required.mjs
deleted file mode 100644
index 5444ae84b..000000000
--- a/tools/scripts/canary/canary_required.mjs
+++ /dev/null
@@ -1,42 +0,0 @@
-import { join } from 'node:path';
-import { readFile } from 'node:fs/promises';
-
-const [, , commentBody] = process.argv;
-
-const LINE_START = 'Used changeset: ';
-
-const previousChangesets = (
- commentBody
- .split('\n')
- .find((line) => line.includes(LINE_START))
- ?.replace(LINE_START, '') ?? '[]'
-)
- .split(',')
- .map((changeset) => changeset.replaceAll('[', '').replaceAll(']', ''))
- .filter(Boolean);
-
-const { changesets: usedChangesets } = await readFile(
- join(process.cwd(), '.changeset', 'pre.json'),
- 'utf-8'
-).then(JSON.parse);
-
-previousChangesets.sort();
-usedChangesets.sort();
-
-const skipCanary = isArraysEquals(previousChangesets, usedChangesets)
- ? 'skip'
- : '';
-
-console.log(`previousChangesets="${JSON.stringify(previousChangesets)}"`);
-console.log(`usedChangesets="${JSON.stringify(usedChangesets)}"`);
-console.log(`skipCanary=${skipCanary}`);
-
-// utils
-
-function isArraysEquals(a, b) {
- if (a.length !== b.length) {
- return false;
- }
-
- return a.every((item, index) => item === b[index]);
-}
diff --git a/tools/scripts/canary/canary_version_restore.mjs b/tools/scripts/canary/canary_version_restore.mjs
deleted file mode 100644
index 95f9d7223..000000000
--- a/tools/scripts/canary/canary_version_restore.mjs
+++ /dev/null
@@ -1,71 +0,0 @@
-import { execSync } from 'node:child_process';
-import { readFile, writeFile } from 'node:fs/promises';
-import * as path from 'node:path';
-
-import { getPackagesInfo } from '../shared/packages.mjs';
-
-const [, , branch] = process.argv;
-
-console.log(`Canary name is ${branch}`);
-
-const packages = await getPackagesInfo();
-
-const canaryNames = packages.map(({ name }) => `@farfetched-canary/${name}`);
-
-const canaryVersions = new Set(
- canaryNames
- .flatMap((canaryName) => {
- try {
- const versions = JSON.parse(
- execSync(`npm view ${canaryName} versions --json`).toString().trim()
- );
- return versions;
- } catch (e) {
- return [];
- }
- })
- .filter((version) => version.includes(`-${branch}.`))
-);
-
-console.log(
- `Found canary versions: ${JSON.stringify(Array.from(canaryVersions))}`
-);
-
-let latestCanaryVerisonSuffix = -1;
-let latestCanaryVerison = null;
-
-for (const canaryVersion of canaryVersions.values()) {
- const [_, suffix] = canaryVersion.split(`-${branch}.`);
-
- const suffixNumber = Number(suffix);
-
- if (suffixNumber > latestCanaryVerisonSuffix) {
- latestCanaryVerisonSuffix = suffixNumber;
- latestCanaryVerison = canaryVersion;
- }
-}
-
-if (latestCanaryVerison) {
- console.log(`Latest canary version: ${latestCanaryVerison}`);
-
- for (const { root } of packages) {
- const packageJsonPath = path.join(process.cwd(), root, 'package.json');
-
- const originalPackageJson = await readFile(packageJsonPath, 'utf-8').then(
- JSON.parse
- );
-
- const nextPackageJson = {
- ...originalPackageJson,
- version: latestCanaryVerison,
- };
-
- await writeFile(packageJsonPath, JSON.stringify(nextPackageJson));
-
- console.log(
- `Updated ${packageJsonPath} with version: ${nextPackageJson.version}`
- );
- }
-} else {
- console.log(`No canary versions found`);
-}
diff --git a/tools/scripts/shared/packages.mjs b/tools/scripts/shared/packages.mjs
deleted file mode 100644
index 22134f8c5..000000000
--- a/tools/scripts/shared/packages.mjs
+++ /dev/null
@@ -1,31 +0,0 @@
-import { readFile, readdir, stat } from 'node:fs/promises';
-import * as path from 'node:path';
-
-export async function getPackagesInfo() {
- const PACKAGES_PATH = 'packages';
-
- const inDirList = await readdir(PACKAGES_PATH);
-
- const packages = [];
-
- await Promise.all(
- inDirList.map(async (dir) => {
- const stats = await stat(path.join(PACKAGES_PATH, dir));
- if (!stats.isDirectory()) {
- return;
- }
-
- const packageJson = await readFile(
- path.join(PACKAGES_PATH, dir, 'package.json'),
- 'utf-8'
- ).then(JSON.parse);
-
- packages.push({
- name: packageJson.name.replace('@farfetched/', ''),
- root: path.join(PACKAGES_PATH, dir),
- });
- })
- );
-
- return packages;
-}