Compare commits

..

No commits in common. "master" and "0.8.0" have entirely different histories.

231 changed files with 12279 additions and 32736 deletions

23
.eslintrc.js Normal file
View File

@ -0,0 +1,23 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module', // Allows for the use of imports
},
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb-base',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
// Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
'plugin:prettier/recommended',
],
plugins: ['@typescript-eslint', 'prettier'],
rules: {},
settings: {
'import/extensions': ['.js', '.ts'],
},
};

View File

@ -1,128 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2022,
"project": ["./tsconfig.eslint.json"],
"sourceType": "module"
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/strict-type-checked",
"plugin:import/recommended",
"plugin:import/typescript",
"prettier"
],
"plugins": [
"@typescript-eslint",
"import",
"license-header",
"unused-imports"
],
"ignorePatterns": ["**/node_modules/", "**/dist/", "**/build/", "**/public/"],
"rules": {
"eqeqeq": ["error", "always"],
"no-console": ["error"],
"arrow-body-style": ["error", "always"],
"no-empty": [
"error",
{
"allowEmptyCatch": true
}
],
"curly": ["error", "all"],
"no-unused-expressions": ["error"],
"dot-notation": ["off"],
"object-curly-spacing": ["error", "always"],
"padding-line-between-statements": [
"error",
{
"blankLine": "always",
"prev": "multiline-expression",
"next": "*"
},
{
"blankLine": "always",
"prev": "*",
"next": "multiline-expression"
},
{
"blankLine": "always",
"prev": "multiline-block-like",
"next": "*"
},
{
"blankLine": "always",
"prev": "*",
"next": "multiline-block-like"
},
{
"blankLine": "always",
"prev": "multiline-const",
"next": "*"
},
{
"blankLine": "always",
"prev": "*",
"next": "multiline-const"
},
{
"blankLine": "always",
"prev": "multiline-let",
"next": "*"
},
{
"blankLine": "always",
"prev": "*",
"next": "multiline-let"
},
{
"blankLine": "any",
"prev": "case",
"next": "case"
}
],
"import/extensions": ["error", "ignorePackages"],
"import/no-unresolved": "off",
"import/no-cycle": ["error"],
"import/order": [
"error",
{
"newlines-between": "always",
"alphabetize": {
"order": "asc",
"caseInsensitive": true
}
}
],
"node/no-unsupported-features/es-syntax": "off",
"node/no-unpublished-import": "off",
"node/no-missing-import": "off",
"@typescript-eslint/explicit-member-accessibility": [
"error",
{
"accessibility": "no-public"
}
],
"@typescript-eslint/strict-boolean-expressions": [
"error",
{
"allowString": false,
"allowNumber": false,
"allowNullableObject": false,
"allowNullableBoolean": false,
"allowNullableString": false,
"allowNullableNumber": false,
"allowAny": false
}
],
"@typescript-eslint/consistent-type-assertions": [
"error",
{
"assertionStyle": "never"
}
],
"unused-imports/no-unused-imports": "error",
"license-header/header": ["error", "./resources/license-header.js"]
}
}

View File

@ -1,3 +0,0 @@
self-hosted-runner:
labels:
- builder

View File

@ -1,208 +0,0 @@
networks:
nox:
driver: bridge
ipam:
config:
- subnet: 10.50.10.0/24
services:
aurora:
image: docker.fluence.dev/aurora:0.2.11
ports:
- 8545:8545
networks:
nox:
ipfs:
image: ipfs/go-ipfs
ports:
- 5001:5001
- 4001:4001
environment:
IPFS_PROFILE: server
volumes:
- ./ipfs/:/container-init.d/
networks:
nox:
ipv4_address: 10.50.10.100
nox-1:
image: ${NOX_IMAGE}
ports:
- 7771:7771
- 9991:9991
environment:
FLUENCE_ENV_AQUA_IPFS_EXTERNAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
FLUENCE_ENV_CONNECTOR_API_ENDPOINT: http://aurora:8545
FLUENCE_ENV_CONNECTOR_CONTRACT_ADDRESS: "0xea6777e8c011E7968605fd012A9Dd49401ec386C"
FLUENCE_ENV_CONNECTOR_FROM_BLOCK: earliest
FLUENCE_ENV_AQUA_IPFS_LOCAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
RUST_LOG: "info,aquamarine=warn,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,cranelift_codegen=info,wasmer_wasi=info,run-console=debug"
command:
- --aqua-pool-size=2
- -t=7771
- -w=9991
- -x=10.50.10.10
- --external-maddrs
- /ip4/127.0.0.1/tcp/7771
- /ip4/127.0.0.1/tcp/9991/ws
- --allow-private-ips
- --local
# - --bootstraps=/dns/nox-1/tcp/7771
# 12D3KooWBM3SdXWqGaawQDGQ6JprtwswEg3FWGvGhmgmMez1vRbR
- -k=hK62afickoeP2uZbmSkAYXxxqP8ozq16VRN7qfTP719EHC5V5tjrtW57BSjUr8GvsEXmJRbtejUWyPZ2rZMyQdq
depends_on:
- ipfs
networks:
nox:
ipv4_address: 10.50.10.10
nox-2:
image: ${NOX_IMAGE}
ports:
- 7772:7772
- 9992:9992
environment:
FLUENCE_ENV_AQUA_IPFS_EXTERNAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
FLUENCE_ENV_CONNECTOR_API_ENDPOINT: http://aurora:8545
FLUENCE_ENV_CONNECTOR_CONTRACT_ADDRESS: "0xea6777e8c011E7968605fd012A9Dd49401ec386C"
FLUENCE_ENV_CONNECTOR_FROM_BLOCK: earliest
FLUENCE_ENV_AQUA_IPFS_LOCAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
RUST_LOG: "info,aquamarine=warn,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,cranelift_codegen=info,wasmer_wasi=info,run-console=debug"
command:
- --aqua-pool-size=2
- -t=7772
- -w=9992
- -x=10.50.10.20
- --external-maddrs
- /ip4/127.0.0.1/tcp/7772
- /ip4/127.0.0.1/tcp/9992/ws
- --allow-private-ips
- --bootstraps=/dns/nox-1/tcp/7771
# 12D3KooWQdpukY3p2DhDfUfDgphAqsGu5ZUrmQ4mcHSGrRag6gQK
- -k=2WijTVdhVRzyZamWjqPx4V4iNMrajegNMwNa2PmvPSZV6RRpo5M2fsPWdQr22HVRubuJhhSw8BrWiGt6FPhFAuXy
depends_on:
- ipfs
networks:
nox:
ipv4_address: 10.50.10.20
nox-3:
image: ${NOX_IMAGE}
ports:
- 7773:7773
- 9993:9993
environment:
FLUENCE_ENV_AQUA_IPFS_EXTERNAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
FLUENCE_ENV_CONNECTOR_API_ENDPOINT: http://aurora:8545
FLUENCE_ENV_CONNECTOR_CONTRACT_ADDRESS: "0xea6777e8c011E7968605fd012A9Dd49401ec386C"
FLUENCE_ENV_CONNECTOR_FROM_BLOCK: earliest
FLUENCE_ENV_AQUA_IPFS_LOCAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
RUST_LOG: "info,aquamarine=warn,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,cranelift_codegen=info,wasmer_wasi=info,run-console=debug"
command:
- --aqua-pool-size=2
- -t=7773
- -w=9993
- -x=10.50.10.30
- --external-maddrs
- /ip4/127.0.0.1/tcp/7773
- /ip4/127.0.0.1/tcp/9993/ws
- --allow-private-ips
- --bootstraps=/dns/nox-1/tcp/7771
# 12D3KooWRT8V5awYdEZm6aAV9HWweCEbhWd7df4wehqHZXAB7yMZ
- -k=2n2wBVanBeu2GWtvKBdrYK9DJAocgG3PrTUXMharq6TTfxqTL4sLdXL9BF23n6rsnkAY5pR9vBtx2uWYDQAiZdrX
depends_on:
- ipfs
networks:
nox:
ipv4_address: 10.50.10.30
nox-4:
image: ${NOX_IMAGE}
ports:
- 7774:7774
- 9994:9994
environment:
FLUENCE_ENV_AQUA_IPFS_EXTERNAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
FLUENCE_ENV_CONNECTOR_API_ENDPOINT: http://aurora:8545
FLUENCE_ENV_CONNECTOR_CONTRACT_ADDRESS: "0xea6777e8c011E7968605fd012A9Dd49401ec386C"
FLUENCE_ENV_CONNECTOR_FROM_BLOCK: earliest
FLUENCE_ENV_AQUA_IPFS_LOCAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
RUST_LOG: "info,aquamarine=warn,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,cranelift_codegen=info,wasmer_wasi=info,run-console=debug"
command:
- --aqua-pool-size=2
- -t=7774
- -w=9994
- -x=10.50.10.40
- --external-maddrs
- /ip4/127.0.0.1/tcp/7774
- /ip4/127.0.0.1/tcp/9994/ws
- --allow-private-ips
- --bootstraps=/dns/nox-1/tcp/7771
# 12D3KooWBzLSu9RL7wLP6oUowzCbkCj2AGBSXkHSJKuq4wwTfwof
- -k=4zp8ucAikkjB8CmkufYiFBW4QCDUCbQG7yMjviX7W8bMyN5rfChQ2Pi5QCWThrCTbAm9uq5nbFbxtFcNZq3De4dX
depends_on:
- ipfs
networks:
nox:
ipv4_address: 10.50.10.40
nox-5:
image: ${NOX_IMAGE}
ports:
- 7775:7775
- 9995:9995
environment:
FLUENCE_ENV_AQUA_IPFS_EXTERNAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
FLUENCE_ENV_CONNECTOR_API_ENDPOINT: http://aurora:8545
FLUENCE_ENV_CONNECTOR_CONTRACT_ADDRESS: "0xea6777e8c011E7968605fd012A9Dd49401ec386C"
FLUENCE_ENV_CONNECTOR_FROM_BLOCK: earliest
FLUENCE_ENV_AQUA_IPFS_LOCAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
RUST_LOG: "info,aquamarine=warn,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,cranelift_codegen=info,wasmer_wasi=info,run-console=debug"
command:
- --aqua-pool-size=2
- -t=7775
- -w=9995
- -x=10.50.10.50
- --external-maddrs
- /ip4/127.0.0.1/tcp/7775
- /ip4/127.0.0.1/tcp/9995/ws
- --allow-private-ips
- --bootstraps=/dns/nox-1/tcp/7771
# 12D3KooWBf6hFgrnXwHkBnwPGMysP3b1NJe5HGtAWPYfwmQ2MBiU
- -k=3ry26rm5gkJXvdqRH4FoM3ezWq4xVVsBQF7wtKq4E4pbuaa6p1F84tNqifUS7DdfJL9hs2gcdW64Wc342vHZHMUp
depends_on:
- ipfs
networks:
nox:
ipv4_address: 10.50.10.50
nox-6:
image: ${NOX_IMAGE}
ports:
- 7776:7776
- 9996:9996
environment:
FLUENCE_ENV_AQUA_IPFS_EXTERNAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
FLUENCE_ENV_CONNECTOR_API_ENDPOINT: http://aurora:8545
FLUENCE_ENV_CONNECTOR_CONTRACT_ADDRESS: "0xea6777e8c011E7968605fd012A9Dd49401ec386C"
FLUENCE_ENV_CONNECTOR_FROM_BLOCK: earliest
FLUENCE_ENV_AQUA_IPFS_LOCAL_API_MULTIADDR: "/ip4/10.50.10.100/tcp/5001"
RUST_LOG: "info,aquamarine=warn,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,cranelift_codegen=info,wasmer_wasi=info,run-console=debug"
command:
- --aqua-pool-size=2
- -t=7776
- -w=9996
- --bootstraps=/dns/nox-1/tcp/7771
- -x=10.50.10.60
- --external-maddrs
- /ip4/127.0.0.1/tcp/7776
- /ip4/127.0.0.1/tcp/9996/ws
- --allow-private-ips
# 12D3KooWPisGn7JhooWhggndz25WM7vQ2JmA121EV8jUDQ5xMovJ
- -k=5Qh8bB1sF28uLPwr3HTvEksCeC6mAWQvebCfcgv9y6j4qKwSzNKm2tzLUg4nACUEo2KZpBw11gNCnwaAdM7o1pEn
depends_on:
- ipfs
networks:
nox:
ipv4_address: 10.50.10.60

View File

@ -1,12 +0,0 @@
#!/bin/sh
ipfs bootstrap rm --all
ipfs config Addresses.API "/ip4/0.0.0.0/tcp/5001"
ipfs config Addresses.Gateway "/ip4/0.0.0.0/tcp/8001"
ipfs config --json Addresses.Swarm '["/ip4/0.0.0.0/tcp/4001", "/ip4/0.0.0.0/tcp/4001/ws"]'
ipfs config --json Addresses.Announce '["/ip4/10.50.10.1/tcp/4001", "/ip4/10.50.10.1/tcp/4001/ws"]'
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "POST"]'
ipfs config --json Pubsub.Enabled true

View File

@ -1,18 +0,0 @@
{
"release-type": "node",
"bump-minor-pre-major": true,
"bump-patch-for-minor-pre-major": true,
"plugins": [
{
"type": "node-workspace"
}
],
"packages": {
"packages/core/js-client": {},
"packages/core/js-client-isomorphic": {},
"packages/core/marine-worker": {},
"packages/core/aqua-to-js": {},
"packages/core/interfaces": {},
"packages/core/npm-aqua-compiler": {}
}
}

View File

@ -1,8 +0,0 @@
{
"packages/core/js-client": "0.9.0",
"packages/core/marine-worker": "0.6.0",
"packages/core/aqua-to-js": "0.3.13",
"packages/core/js-client-isomorphic": "0.6.0",
"packages/core/interfaces": "0.12.0",
"packages/core/npm-aqua-compiler": "0.0.3"
}

37
.github/renovate.json vendored
View File

@ -1,37 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base",
":semanticCommitTypeAll(chore)"
],
"prBodyTemplate": "{{{header}}}{{{table}}}{{{warnings}}}{{{notes}}}{{{configDescription}}}{{{controls}}}{{{footer}}}",
"enabledManagers": ["npm", "github-actions"],
"rangeStrategy": "pin",
"schedule": "every weekend",
"respectLatest": false,
"packageRules": [
{
"matchManagers": ["npm"],
"matchPackagePatterns": [
"@fluencelabs/.*"
],
"semanticCommitType": "fix",
"semanticCommitScope": "deps",
"schedule": "at any time"
},
{
"matchDepTypes": ["devDependencies"],
"prPriority": -1,
"semanticCommitType": "chore",
"semanticCommitScope": "deps"
},
{
"matchUpdateTypes": ["major"],
"prConcurrentLimit": 1
},
{
"matchManagers": ["github-actions"],
"groupName": "all github-actions"
}
]
}

View File

@ -1,54 +0,0 @@
name: "e2e"
on:
pull_request:
paths-ignore:
- "**.md"
- ".github/**"
- "!.github/workflows/e2e.yml"
- "!.github/workflows/tests.yml"
- "!.github/workflows/snapshot.yml"
types:
- "labeled"
- "synchronize"
- "opened"
- "reopened"
push:
branches:
- "main"
paths-ignore:
- "**.md"
- ".github/**"
- "!.github/workflows/e2e.yml"
- "!.github/workflows/tests.yml"
- "!.github/workflows/snapshot.yml"
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: true
jobs:
js-client:
if: >
github.event_name == 'push' ||
contains(github.event.pull_request.labels.*.name, 'e2e')
uses: ./.github/workflows/snapshot.yml
with:
ref: ${{ github.ref }}
aqua:
needs:
- js-client
uses: fluencelabs/aqua/.github/workflows/tests.yml@main
with:
js-client-snapshots: "${{ needs.js-client.outputs.js-client-snapshots }}"
nox-image: "docker.fluence.dev/nox:renovate-avm_4905_1"
flox:
needs:
- js-client
uses: fluencelabs/flox/.github/workflows/tests.yml@main
with:
js-client-snapshots: "${{ needs.js-client.outputs.js-client-snapshots }}"
nox-image: "docker.fluence.dev/nox:renovate-avm_4905_1"

39
.github/workflows/js_sdk_ci.yml vendored Normal file
View File

@ -0,0 +1,39 @@
name: Node.js CI
defaults:
run:
working-directory: .
on:
push:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 15.x]
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-${{ matrix.node-version }}
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
env:
CI: true

View File

@ -1,35 +0,0 @@
name: lint
on:
pull_request:
types:
- opened
- edited
- synchronize
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: true
jobs:
pr:
name: Validate PR title
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
reviewdog:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Lint actions
uses: reviewdog/action-actionlint@v1
env:
SHELLCHECK_OPTS: "-e SC2086 -e SC2207 -e SC2128"
with:
reporter: github-pr-check
fail_on_error: true

83
.github/workflows/publish_branch.yml vendored Normal file
View File

@ -0,0 +1,83 @@
name: "publish-branch"
on:
push:
jobs:
npm-publish:
name: "Publish"
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
### Extract branch name
- name: Extract branch name
if: github.event_name != 'pull_request'
run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/})" >> $GITHUB_ENV
id: extract_branch
- name: Extract branch name
if: github.event_name == 'pull_request'
run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/})" >> $GITHUB_ENV
- name: Checkout repository
uses: actions/checkout@v2
### Calculate FINAL_VERSION
- name: Install jq
run: sudo apt-get update && sudo apt-get --yes --force-yes install jq
- name: Get version from npm and increment
run: |
# install semver and add it to PATH
yarn global add semver
PATH="$(yarn global bin):$PATH"
# sanitize branch name so it can be used as a semver suffix (replace [^0-9a-zA-Z-] with hyphen)
SANITIZED_BRANCH="$(echo -n "${{ env.BRANCH_NAME }}" | tr -C '[:alnum:]-' -)"
# get package name from package.json
PKG_NAME="$(cat package.json | jq -r .name)"
# take all versions from npm and replace single quotes with double quotes
NPM_VERSIONS=$(yarn info --silent "$PKG_NAME" versions 2>/dev/null | tr \' \")
# take only versions that contain branch name
NPM_VERSIONS_FILTERED=$(echo $NPM_VERSIONS | jq -r ".[] | select(contains(\"$SANITIZED_BRANCH\"))")
# flatten into a single line
NPM_VERSIONS_FLATTENED=$(echo $NPM_VERSIONS_FILTERED | awk '{print}' ORS=' ')
# sort versions according to semver, take highest (last)
LAST_NPM_VERSION="$(semver -p $(echo $NPM_VERSIONS_FLATTENED) | tail -n1 || true)"
# increment prerelease part of the version
PRERELEASE_NPM_VERSION="$(semver --increment prerelease --preid "$SANITIZED_BRANCH" "${LAST_NPM_VERSION}" || true)"
# take local version
LOCAL_VERSION="$(cat package.json | jq -r .version)"
# set prerelease part on local version
LOCAL_PRERELEASE_VERSION="$(semver --increment prerelease --preid "$SANITIZED_BRANCH" "${LOCAL_VERSION}-0")" # added '-0' here to avoid semver erroneously increment patch octet. Any suffix works, '-0' is chosen deliberately.
# take the highest version
MAX_VERSION="$(semver "$LOCAL_PRERELEASE_VERSION" "$PRERELEASE_NPM_VERSION" | tail -n1)"
# save info to env
echo "FINAL_VERSION=$MAX_VERSION" | tee -a $GITHUB_ENV
echo "PKG_NAME=$PKG_NAME" | tee -a $GITHUB_ENV
### Set version
- name: Set version to ${{ env.FINAL_VERSION }}
run: yarn version --new-version ${{ env.FINAL_VERSION }} --no-git-tag-version
### Publish to NPM registry
- uses: actions/setup-node@v1
with:
node-version: '15'
registry-url: 'https://registry.npmjs.org'
- run: cat package.json
- run: npm i
- run: npm run build
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

73
.github/workflows/publish_release.yml vendored Normal file
View File

@ -0,0 +1,73 @@
name: "publish-release"
on:
push:
branches:
- "master"
jobs:
npm-publish:
name: "Publish"
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout repository
uses: actions/checkout@v2
### Calculate FINAL_VERSION
- name: Install jq
run: sudo apt-get update && sudo apt-get --yes --force-yes install jq
- name: Get version from npm and increment
run: |
yarn global add semver
PATH="$(yarn global bin):$PATH"
# take npm version and increment it
PKG_NAME="$(cat package.json | jq -r .name)"
NPM_VERSION="$(yarn info --silent "$PKG_NAME" version || true)"
NEXT_NPM_VERSION="$(semver --increment patch "$NPM_VERSION")"
# take local version
LOCAL_VERSION="$(cat package.json | jq -r .version)"
# take maximum of the local and NEXT_NPM versions
MAX_VERSION="$(semver "$LOCAL_VERSION" "$NEXT_NPM_VERSION" "0.0.0" | tail -n1)"
# save info to env
echo "FINAL_VERSION=$MAX_VERSION" | tee -a $GITHUB_ENV
echo "PKG_NAME=$PKG_NAME" | tee -a $GITHUB_ENV
### Set version
- name: Set version to ${{ env.FINAL_VERSION }}
run: yarn version --new-version ${{ env.FINAL_VERSION }} --no-git-tag-version
### Publish to NPM registry
- uses: actions/setup-node@v1
with:
node-version: '14'
registry-url: 'https://registry.npmjs.org'
- run: npm i
- run: npm run build
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
### Create a release
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ env.FINAL_VERSION }}
release_name: Fluence Network ${{ env.FINAL_VERSION }}
body: |
[${{ env.FINAL_VERSION }} @ NPM registry](https://www.npmjs.com/package/${{ env.PKG_NAME }}/v/${{ env.FINAL_VERSION }})
draft: false
prerelease: false

View File

@ -1,168 +0,0 @@
name: "release-please"
on:
push:
branches:
- "main"
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
env:
CI: true
FORCE_COLOR: true
jobs:
release-please:
runs-on: ubuntu-latest
outputs:
release-created: ${{ steps.release.outputs.releases_created }}
pr: ${{ steps.release.outputs.pr }}
steps:
- name: Run release-please
id: release
uses: google-github-actions/release-please-action@v3
with:
token: ${{ secrets.FLUENCEBOT_RELEASE_PLEASE_PAT }}
command: manifest
config-file: .github/release-please/config.json
manifest-file: .github/release-please/manifest.json
- name: Show output from release-please
if: steps.release.outputs.releases_created
env:
RELEASE_PLEASE_OUTPUT: ${{ toJSON(steps.release.outputs) }}
run: echo "${RELEASE_PLEASE_OUTPUT}" | jq
bump-version:
if: needs.release-please.outputs.pr != null
runs-on: ubuntu-latest
needs:
- release-please
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v3
with:
ref: ${{ fromJson(needs.release-please.outputs.pr).headBranchName }}
token: ${{ secrets.FLUENCEBOT_RELEASE_PLEASE_PAT }}
- name: Setup pnpm
uses: pnpm/action-setup@v2.2.4
with:
version: 8
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: "18"
registry-url: "https://registry.npmjs.org"
cache: "pnpm"
- run: pnpm i --no-frozen-lockfile
- name: Commit version bump
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "chore: Regenerate pnpm lock file"
branch: ${{ fromJson(needs.release-please.outputs.pr).headBranchName }}
commit_user_name: fluencebot
commit_user_email: devops@fluence.one
commit_author: fluencebot <devops@fluence.one>
fluence-js:
if: needs.release-please.outputs.release-created
runs-on: ubuntu-latest
needs:
- release-please
permissions:
contents: read
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Import secrets
uses: hashicorp/vault-action@v2.4.3
with:
url: https://vault.fluence.dev
path: jwt/github
role: ci
method: jwt
jwtGithubAudience: "https://github.com/fluencelabs"
jwtTtl: 300
exportToken: false
secrets: |
kv/npmjs/fluencebot token | NODE_AUTH_TOKEN
- name: Setup pnpm
uses: pnpm/action-setup@v2.2.4
with:
version: 8
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: "18"
registry-url: "https://registry.npmjs.org"
cache: "pnpm"
- run: pnpm i
- run: pnpm -r build
- name: Publish to npm registry
run: pnpm --no-git-checks -r publish -filter '@fluencelabs/*' --access public --tag unstable
slack:
if: always()
name: "Notify"
runs-on: ubuntu-latest
needs:
- release-please
- fluence-js
permissions:
contents: read
id-token: write
steps:
- uses: lwhiteley/dependent-jobs-result-check@v1
id: status
with:
statuses: failure
dependencies: ${{ toJSON(needs) }}
- name: Log output
run: |
echo "statuses:" "${{ steps.status.outputs.statuses }}"
echo "jobs:" "${{ steps.status.outputs.jobs }}"
echo "found any?:" "${{ steps.status.outputs.found }}"
- name: Import secrets
uses: hashicorp/vault-action@v2.4.3
with:
url: https://vault.fluence.dev
path: jwt/github
role: ci
method: jwt
jwtGithubAudience: "https://github.com/fluencelabs"
jwtTtl: 300
exportToken: false
secrets: |
kv/slack/release-please webhook | SLACK_WEBHOOK_URL
- uses: ravsamhq/notify-slack-action@v2
if: steps.status.outputs.found == 'true'
with:
status: "failure"
notification_title: "*{workflow}* has {status_message}"
message_format: "${{ steps.status.outputs.jobs }} {status_message} in <{repo_url}|{repo}>"
footer: "<{run_url}>"

View File

@ -1,31 +0,0 @@
name: "test"
on:
pull_request:
paths-ignore:
- "**.md"
- ".github/**"
- "!.github/workflows/e2e.yml"
- "!.github/workflows/tests.yml"
- "!.github/workflows/snapshot.yml"
push:
branches:
- "main"
paths-ignore:
- "**.md"
- ".github/**"
- "!.github/workflows/e2e.yml"
- "!.github/workflows/tests.yml"
- "!.github/workflows/snapshot.yml"
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: true
jobs:
tests:
name: "js-client"
uses: ./.github/workflows/tests.yml
with:
ref: ${{ github.ref }}
nox-image: "docker.fluence.dev/nox:renovate-avm_4905_1"

View File

@ -1,95 +0,0 @@
name: Publish snapshot
on:
workflow_call:
inputs:
avm-version:
description: "@fluencelabs/avm version"
type: string
default: "null"
marine-js-version:
description: "@fluencelabs/marine-js version"
type: string
default: "null"
ref:
description: "git ref to checkout to"
type: string
default: "main"
outputs:
js-client-snapshots:
description: "js-client snapshots"
value: ${{ jobs.publish-snapshot.outputs.snapshots }}
env:
FORCE_COLOR: true
CI: true
jobs:
publish-snapshot:
name: "Publish snapshot"
runs-on: builder
outputs:
snapshots: "${{ steps.snapshot.outputs.snapshots }}"
permissions:
contents: read
id-token: write
steps:
- name: Checkout js-client
uses: actions/checkout@v3
with:
repository: fluencelabs/js-client
ref: ${{ inputs.ref }}
- uses: pnpm/action-setup@v2.2.4
with:
version: 8
- name: Setup node with self-hosted npm registry
uses: actions/setup-node@v3
with:
node-version: "16"
registry-url: "https://npm.fluence.dev"
cache: "pnpm"
- name: Override dependencies
uses: fluencelabs/github-actions/pnpm-set-dependency@main
with:
dependencies: |
{
"@fluencelabs/avm": "${{ inputs.avm-version }}",
"@fluencelabs/marine-js": "${{ inputs.marine-js-version }}"
}
- run: pnpm -r --no-frozen-lockfile i
- name: Import secrets
uses: hashicorp/vault-action@v2.4.3
with:
url: https://vault.fluence.dev
path: jwt/github
role: ci
method: jwt
jwtGithubAudience: "https://github.com/fluencelabs"
jwtTtl: 300
exportToken: false
secrets: |
kv/npm-registry/basicauth/ci token | NODE_AUTH_TOKEN
- name: Generate snapshot version
id: version
uses: fluencelabs/github-actions/generate-snapshot-id@main
- name: Set package version
run: node ci.cjs bump-version ${{ steps.version.outputs.id }}
- run: pnpm -r build
- name: Publish snapshots
id: snapshot
uses: fluencelabs/github-actions/pnpm-publish-snapshot@main
with:
id: ${{ steps.version.outputs.id }}
set-version: false

View File

@ -1,113 +0,0 @@
name: Run tests with worflow_call
on:
workflow_call:
inputs:
nox-image:
description: "nox image tag"
type: string
default: "fluencelabs/nox:0.4.2"
avm-version:
description: "@fluencelabs/avm version"
type: string
default: "null"
marine-js-version:
description: "@fluencelabs/marine-js version"
type: string
default: "null"
ref:
description: "git ref to checkout to"
type: string
default: "main"
env:
NOX_IMAGE: "${{ inputs.nox-image }}"
FORCE_COLOR: true
CI: true
jobs:
js-client:
name: "Run tests"
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
env:
LATEST_NODE_VERSION: 20.x
strategy:
matrix:
node-version:
- 18.x
- 20.x
steps:
- name: Import secrets
uses: hashicorp/vault-action@v2.4.3
with:
url: https://vault.fluence.dev
path: jwt/github
role: ci
method: jwt
jwtGithubAudience: "https://github.com/fluencelabs"
jwtTtl: 300
secrets: |
kv/docker-registry/basicauth/ci username | DOCKER_USERNAME ;
kv/docker-registry/basicauth/ci password | DOCKER_PASSWORD
- name: Login to DockerHub
uses: docker/login-action@v2
with:
registry: docker.fluence.dev
username: ${{ env.DOCKER_USERNAME }}
password: ${{ env.DOCKER_PASSWORD }}
- name: Checkout
uses: actions/checkout@v3
with:
repository: fluencelabs/fluence-js
ref: ${{ inputs.ref }}
- name: Pull nox image
run: docker pull $NOX_IMAGE
- name: Run nox network
uses: isbang/compose-action@v1.4.1
with:
compose-file: ".github/e2e/docker-compose.yml"
down-flags: "--volumes"
- name: Setup pnpm
uses: pnpm/action-setup@v2.2.4
with:
version: 8
- name: Setup node ${{ matrix.node-version }} with self-hosted registry
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
registry-url: "https://npm.fluence.dev"
cache: "pnpm"
- name: Override dependencies
uses: fluencelabs/github-actions/pnpm-set-dependency@main
with:
dependencies: |
{
"@fluencelabs/avm": "${{ inputs.avm-version }}",
"@fluencelabs/marine-js": "${{ inputs.marine-js-version }}"
}
- run: pnpm -r --no-frozen-lockfile i
- run: pnpm -r build
- name: Lint code
run: pnpm lint-check
- run: pnpm -r test
- name: Dump container logs
if: always()
uses: jwalton/gh-docker-logs@v2

18
.gitignore vendored
View File

@ -1,11 +1,15 @@
# Logs
logs
*.log
.idea
.eslintcache
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
# Dependency directories
node_modules/
# Build directory
dist/
public/
.DS_Store
jspm_packages/

3
.npmrc
View File

@ -1,3 +0,0 @@
auto-install-peers=true
save-exact=true
side-effects-cache=false

View File

@ -1,16 +0,0 @@
.github
.eslintcache
pnpm-lock.yaml
node_modules
dist
build
public
**/CHANGELOG.md
# TODO: remove after pnpm-set-deps will add \n symbol at the end of these files
**/package.json
packages/core/js-client-isomorphic/src/versions.ts
__snapshots__
packages/@tests/aqua/src/_aqua/**

View File

@ -1 +0,0 @@
{}

8
.prettierrc.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false
};

View File

@ -1,13 +0,0 @@
## Contribute Code
You are welcome to contribute to Fluence!
Things you need to know:
1. You need to **agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7) (CLA)**. This is a common practice in all major Open Source projects. At the current moment, we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
2. **Not all proposed contributions can be accepted**. Some features may, e.g., just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
### Contributor License Agreement
When you contribute, you have to be aware that your contribution is covered by **[Apache License 2.0](./LICENSE)**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**. In particular, you need to agree to the Contributor License Agreement. If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. The CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.

View File

@ -1,49 +0,0 @@
# Setting up dev environment
JS Client uses pnpm to manage monorepo packages. See [pnpm.io](https://pnpm.io/installation) for installation instructions.
Install dependencies
```bash
pnpm install
```
Build all packages
```
pnpm -r build
```
# Running tests
Tests are split into unit and integration categories. By default integration tests require a locally running Fluence node with 4310 port open for ws connections. The dependency can be started with docker
```bash
docker run --rm -e RUST_LOG="info" -p 1210:1210 -p 4310:4310 fluencelabs/fluence -t 1210 -w 4310 -k gKdiCSUr1TFGFEgu2t8Ch1XEUsrN5A2UfBLjSZvfci9SPR3NvZpACfcpPGC3eY4zma1pk7UvYv5zb1VjvPHwCjj
```
To run all tests
```bash
pnpm -r test
```
To run only unit tests
```bash
pnpm -r test:unit
```
To run only integration tests
```bash
pnpm -r test:integration
```
# Repo structure:
TBD
# Architecture
TBD

201
LICENSE
View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

197
README.md
View File

@ -1,194 +1,31 @@
# Fluence JS Client
# Fluence browser client
[![npm](https://img.shields.io/npm/v/@fluencelabs/js-client?label=@fluencelabs/js-client)](https://www.npmjs.com/package/@fluencelabs/js-client)
[![npm version](https://badge.fury.io/js/%40fluencelabs%2Ffluence.svg)](https://badge.fury.io/js/%40fluencelabs%2Ffluence)
This is the Javascript client for the [Fluence](https://fluence.network) network. The main role of the JS client is to connect to the Fluence Network and allow you to integrate Aqua code into your application.
Browser client for the Fluence network based on the js-libp2p.
## Installation
## How to build
> JS Client only supports the ESM format that means not every Node.js project can install it.
> You can read more [here](https://nodejs.org/api/esm.html)
With `npm` installed building could be done as follows:
1. Install the client:
```bash
npm i @fluencelabs/js-client
```
2. Add the following lines at the beginning of your code:
```javascript
import { Fluence, randomKras } from "@fluencelabs/js-client";
Fluence.connect(randomKras());
```
### HTML page
Add a script tag with the JS Client module to your `index.html`. The easiest way to do this is using a CDN (
like [JSDELIVR](https://www.jsdelivr.com/) or [UNPKG](https://unpkg.com/)).
Here is an example using the JSDELIVR CDN:
```html
<head>
<title>Cool App</title>
<script type="module">
import {
Fluence,
randomKras,
} from "https://cdn.jsdelivr.net/npm/@fluencelabs/js-client/dist/browser/index.min.js";
Fluence.connect(randomKras());
</script>
</head>
```bash
npm install fluence
```
If you cannot or don't want to use a CDN, feel free to get the script directly from
the [npm package](https://www.npmjs.com/package/@fluencelabs/js-client) and host it yourself. You can find the script in
the `/dist/browser` directory of the package. (Note: this option means that developers understand what they are doing and know
how to serve this file from their own web server.)
## Example
## Usage in an Application
Shows how to register and call new service in Fluence network.
Once you've added the client, you can compile [Aqua](https://github.com/fluencelabs/aqua) and run it in your application. To compile Aqua, use [Fluence CLI](https://github.com/fluencelabs/cli).
1. Install the package:
```bash
npm i -D @fluencelabs/cli
```
2. Add a directory in your project for Aqua code, e.g., `_aqua`.
3. Put `*.aqua` files in that directory.
4. Add a directory for compiled Aqua files inside your sources. For example, if your app source is located in the `src` directory, you can create `src/_aqua`.
5. To compile Aqua code once, run `npx fluence aqua -i ./_aqua -o ./src/_aqua/`. To watch the changes and to recompile on the fly, add the `-w` flag: `npx fluence aqua -w -i ./_aqua -o ./src/_aqua/`.
**Hint**: it might be a good idea to add these scripts to your `package.json` file.
For example, you project structure could look like this:
```
┣ _aqua
┃ ┗ demo.aqua
┣ src
┃ ┣ _aqua
┃ ┃ ┗ demo.ts
┃ ┗ index.ts
┣ package-lock.json
┣ package.json
┗ tsconfig.json
```
Then, your `package.json` file should include the following lines:
```
{
...
"scripts": {
...
"aqua:compile": "fluence aqua -i ./aqua/ -o ./src/_aqua",
"aqua:watch": "fluence aqua -w -i ./aqua/ -o ./src/_aqua"
},
...
}
```
6. Now you can import and call Aqua code from your application like
this:
```javascript
import { getRelayTime } from "./_aqua/demo";
async function buttonClick() {
const time = await getRelayTime();
alert("relay time: " + time);
}
```
## Debug
JS Client uses the [debug](https://github.com/debug-js/debug) library under the hood for logging. The log namespaces are structured on a per-component basis, following this structure:
```
fluence:<component>:trace
fluence:<component>:debug
fluence:<component>:error
Generate new peer ids for clients.
```typescript
let peerId1 = await Fluence.generatePeerId();
let peerId2 = await Fluence.generatePeerId();
```
Marine JS logs have a slightly different structure:
Establish connections to predefined nodes.
```typescript
let client1 = await Fluence.connect("/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb", peerId1);
let client2 = await Fluence.connect("/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er", peerId2);
```
fluence:marine:<service id>:trace
fluence:marine:<service id>:debug
fluence:marine:<service id>:info
fluence:marine:<service id>:warn
fluence:marine:<service id>:error
```
Each level corresponds to a logging level in Marine JS.
Star (`*`) character can be used as a wildcard to enable logs for multiple components at once. For example, `DEBUG=fluence:*` will enable logs for all components. To exclude a component, use a minus sign before the component name. For example, `DEBUG=fluence:*,-fluence:particle:*`
### Index of components:
- `particle`: everything related to particle processing queue
- `aqua`: infrastructure of aqua compiler support
- `connection`: connection layer
- `marine`: Marine JS logs
### Enabling logs in Node.js
Enable logs by passing the environment variable `DEBUG` with the corresponding log level. For example:
```sh
DEBUG=fluence:* node --loader ts-node/esm ./src/index.ts
```
### Enabling logs in the browser
To enable logs, set the `localStorage.debug` variable. For example:
```javascript
localStorage.debug = "fluence:*";
```
**NOTE**
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will be default—only to show
messages logged by debug if the "Verbose" log level is enabled.
## Low level usage
JS client also has an API for low level interaction with AVM and Marine JS.
It could be handy in advanced scenarios when a user fetches AIR dynamically or generates AIR without default Aqua compiler.
`callAquaFunction` Allows to call aqua function without schema.
`registerService` Gives an ability to register service without schema. Passed `service` could be
- Plain object. In this case all function properties will be registered as AIR service functions.
- Class instance. All class methods without inherited ones will be registered as AIR service functions.
## Development
To hack on the Fluence JS Client itself, please refer to the [development page](./DEVELOPING.md).
## Documentation
The starting point for all documentation related to Fluence is
[fluence.dev](https://fluence.dev/). We also have an active [YouTube channel](https://www.youtube.com/@fluencelabs).
## Support
Please, file an [issue](https://github.com/fluencelabs/js-client/issues) if you find a bug. You can also contact us at [Discord](https://discord.com/invite/5qSnPZKh7u) or [Telegram](https://t.me/fluence_project). We will do our best to resolve the issue ASAP.
## Contributing
Any interested person is welcome to contribute to the project. Please, make sure you read and follow some basic [rules](./CONTRIBUTING.md).
## License
All software code is copyright (c) Fluence Labs, Inc. under the [Apache-2.0](./LICENSE) license.

166
ci.cjs
View File

@ -1,166 +0,0 @@
#! /usr/bin/env node
const fs = require("fs").promises;
const path = require("path");
function printUsage() {
console.log(
`Usage: "ci check-consistency" or "ci bump-version %postfix%" or "ci get-version"`,
);
}
let postfix;
const mode = process.argv[2];
function validateArgs() {
switch (mode) {
case "get-version":
return true;
case "bump-version":
postfix = process.argv[3];
if (!postfix) {
printUsage();
process.exit();
}
return true;
case "":
case undefined:
case "check-consistency":
return true;
default:
return false;
}
}
const PATH_TO_PACKAGES = "./packages/";
async function getPackageJsonsRecursive(currentPath) {
return (
await Promise.all(
(await fs.readdir(currentPath, { withFileTypes: true }))
.filter(
(file) =>
file.name !== "node_modules" &&
file.name !== "@tests" &&
(file.isDirectory() || file.name === "package.json"),
)
.map((file) =>
file.isDirectory()
? getPackageJsonsRecursive(path.join(currentPath, file.name))
: Promise.resolve([
path.join(process.cwd(), currentPath, file.name),
]),
),
)
).flat();
}
async function getVersion(file) {
const content = await fs.readFile(file);
const json = JSON.parse(content);
return [json.name, json.version];
}
function processDep(obj, name, fn) {
if (!obj) {
return;
}
if (!obj[name]) {
return;
}
fn(obj, obj[name]);
}
async function getVersionsMap(allPackageJsons) {
return new Map(await Promise.all(allPackageJsons.map(getVersion)));
}
function getVersionForPackageOrThrow(versionsMap, packageName) {
const version = versionsMap.get(packageName);
if (!version) {
console.log("Failed to get version for package: ", packageName);
process.exit(1);
}
return version;
}
async function checkConsistency(file, versionsMap) {
console.log("Checking: ", file);
const content = await fs.readFile(file);
const json = JSON.parse(content);
for (const [name, versionInDep] of versionsMap) {
const check = (x, version) => {
if (version.includes("*") || version.includes("^")) {
return;
}
if (versionInDep !== version) {
console.log(
`Error, versions don't match: ${name}:${version} !== ${versionInDep}`,
file,
);
process.exit(1);
}
};
processDep(json.dependencies, name, check);
processDep(json.devDependencies, name, check);
}
}
async function bumpVersions(file, versionsMap) {
console.log("Updating: ", file);
const content = await fs.readFile(file);
const json = JSON.parse(content);
// bump dependencies
for (const [name, version] of versionsMap) {
const update = (x) => (x[name] = `${version}-${postfix}`);
processDep(json.dependencies, name, update);
processDep(json.devDependencies, name, update);
}
// also bump version in package itself
const version = getVersionForPackageOrThrow(versionsMap, json.name);
json.version = `${version}-${postfix}`;
const newContent = JSON.stringify(json, undefined, 4) + "\n";
await fs.writeFile(file, newContent);
}
async function processPackageJsons(allPackageJsons, versionsMap, fn) {
await Promise.all(allPackageJsons.map((x) => fn(x, versionsMap)));
}
async function run() {
if (!validateArgs()) {
printUsage();
process.exit(0);
}
const packageJsons = await getPackageJsonsRecursive(PATH_TO_PACKAGES);
const versionsMap = await getVersionsMap(packageJsons);
if (mode === "get-version") {
const fjs = versionsMap.get("@fluencelabs/fluence");
console.log(fjs);
return;
}
// always check consistency
console.log("Checking versions consistency...");
await processPackageJsons(packageJsons, versionsMap, checkConsistency);
console.log("Versions are consistent");
if (mode === "bump-version") {
console.log("Adding postfix: ", postfix);
await processPackageJsons(packageJsons, versionsMap, bumpVersions);
console.log("Done");
}
}
run();

9539
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,56 @@
{
"name": "common-dev-deps",
"version": "0.1.0",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"type": "module",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"name": "@fluencelabs/fluence",
"version": "0.8.0",
"description": "JS SDK for the Fluence network",
"main": "./dist/fluence.js",
"typings": "./dist/fluence.d.ts",
"scripts": {
"lint-check": "pnpm run prettier --check && pnpm run eslint",
"lint-fix": "pnpm run prettier --write && pnpm run eslint --fix",
"prettier": "prettier .",
"eslint": "eslint --cache \"**/src/**/*.{js,ts}\""
"test": "mocha --timeout 10000 -r esm -r ts-node/register src/**/*.spec.ts",
"test-ts": "ts-mocha --timeout 10000 -r esm -p tsconfig.json src/**/*.spec.ts",
"package:build": "NODE_ENV=production webpack && npm run package",
"package": "tsc && rsync -r src/aqua/*.js dist/aqua",
"start": "webpack-dev-server -p",
"build": "webpack --mode production"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/aquamarine-stepper": "0.0.30",
"async": "3.2.0",
"base64-js": "1.3.1",
"bs58": "4.0.1",
"cids": "0.8.1",
"it-length-prefixed": "3.0.1",
"it-pipe": "1.1.0",
"libp2p": "0.28.3",
"libp2p-mplex": "0.9.5",
"libp2p-secio": "0.12.5",
"libp2p-websockets": "0.13.6",
"loglevel": "1.7.0",
"peer-id": "0.13.12",
"uuid": "8.3.0"
},
"devDependencies": {
"@total-typescript/ts-reset": "0.5.1",
"@tsconfig/strictest": "2.0.2",
"@types/node": "18.13.0",
"@typescript-eslint/eslint-plugin": "6.7.3",
"@typescript-eslint/parser": "6.7.3",
"eslint": "8.50.0",
"eslint-config-prettier": "9.0.0",
"eslint-plugin-import": "2.28.1",
"eslint-plugin-license-header": "0.6.0",
"eslint-plugin-unused-imports": "3.0.0",
"http-server": "14.1.1",
"prettier": "3.0.3",
"puppeteer": "19.7.2",
"ts-node": "10.9.1",
"typescript": "5.1.6"
"@types/base64-js": "1.2.5",
"@types/bs58": "4.0.1",
"@types/chai": "4.2.11",
"@types/mocha": "7.0.2",
"@types/uuid": "8.3.0",
"assert": "2.0.0",
"chai": "4.2.0",
"clean-webpack-plugin": "3.0.0",
"esm": "^3.2.25",
"html-webpack-plugin": "^3.2.0",
"libp2p-ts": "https://github.com/ChainSafe/libp2p-ts.git#fca072c9764436ef71f974a211bb1befae432575",
"mocha": "^8.2.1",
"mocha-loader": "^5.1.5",
"text-encoding": "^0.7.0",
"ts-loader": "7.0.5",
"ts-mocha": "8.0.0",
"typescript": "3.9.5",
"webpack": "4.43.0",
"webpack-cli": "3.3.11",
"webpack-dev-server": "3.11.0"
}
}

View File

@ -1,6 +0,0 @@
{
"ignorePatterns": ["**/*.css"],
"rules": {
"no-console": "off"
}
}

View File

@ -1,6 +0,0 @@
import "@fluencelabs/aqua-lib/builtin.aqua"
export test
func test():
on HOST_PEER_ID:
Op.noop()

View File

@ -1,58 +0,0 @@
import "@fluencelabs/registry/resources-api.aqua"
service HelloWorld("hello-world"):
hello(str: string) -> string
func resourceTest(label: string) -> ?string, *string:
res, errors <- createResource(label)
<- res, errors
func helloTest() -> string:
hello <- HelloWorld.hello("Fluence user")
<- hello
service CalcService:
add(num: f64) -> f64
clear_state()
divide(num: f64) -> f64
multiply(num: f64) -> f64
state() -> f64
subtract(num: f64) -> f64
test_logs()
data ServiceCreationResult:
success: bool
service_id: ?string
error: ?string
data RemoveResult:
success: bool
error: ?string
alias ListServiceResult: []string
service Srv("single_module_srv"):
create(wasm_b64_content: string) -> ServiceCreationResult
remove(service_id: string) -> RemoveResult
list() -> ListServiceResult
func demo_calculation(service_id: string) -> f64:
CalcService service_id
CalcService.test_logs()
CalcService.add(10)
CalcService.multiply(5)
CalcService.subtract(8)
CalcService.divide(6)
res <- CalcService.state()
<- res
func marineTest(wasm64: string) -> f64:
serviceResult <- Srv.create(wasm64)
res <- demo_calculation(serviceResult.service_id!)
<- res
func callHappy(a: string, b: f64, c: f64, d: string -> f64) -> f64:
res <- d("abc")
<- res

View File

@ -1,51 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { writeFile } from "fs/promises";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { compileFromPath } from "@fluencelabs/aqua-api";
import aquaToJs from "@fluencelabs/aqua-to-js";
const files = ["smoke_test", "finalize_particle"];
for (const file of files) {
const cr = await compileFromPath({
filePath: join(
dirname(fileURLToPath(import.meta.url)),
"_aqua",
file + ".aqua",
),
targetType: "air",
imports: [fileURLToPath(new URL("./node_modules", import.meta.url))],
});
if (cr.errors.length > 0) {
throw new Error(cr.errors.join("\n"));
}
const res = await aquaToJs(cr, "ts");
if (res == null) {
throw new Error("AquaToJs gave null value after compilation");
}
await writeFile(
fileURLToPath(new URL(join("src", "_aqua", file + ".ts"), import.meta.url)),
res.sources,
);
}

View File

@ -1,31 +0,0 @@
{
"name": "@test/aqua_for_test",
"version": "0.1.0",
"description": "Shared aqua code for tests",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"type": "module",
"scripts": {
"build": "tsc",
"compile-aqua": "node --loader ts-node/esm compile-aqua.ts"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"base64-js": "1.5.1"
},
"devDependencies": {
"@fluencelabs/aqua-api": "0.13.0",
"@fluencelabs/aqua-lib": "0.6.0",
"@fluencelabs/aqua-to-js": "workspace:*",
"@fluencelabs/js-client": "workspace:*",
"@fluencelabs/registry": "0.9.0",
"@fluencelabs/trust-graph": "3.1.2",
"ts-node": "10.9.1"
}
}

View File

@ -1,69 +0,0 @@
/* eslint-disable */
// @ts-nocheck
/**
*
* This file is generated using:
* @fluencelabs/aqua-api version: 0.12.4-main-cee4448-2196-1
* @fluencelabs/aqua-to-js version: 0.2.0
* If you find any bugs in generated AIR, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* If you find any bugs in generated JS/TS, please write an issue on GitHub: https://github.com/fluencelabs/js-client/issues
*
*/
import type { IFluenceClient as IFluenceClient$$, ParticleContext as ParticleContext$$ } from '@fluencelabs/js-client';
// Making aliases to reduce chance of accidental name collision
import {
v5_callFunction as callFunction$$,
v5_registerService as registerService$$
} from '@fluencelabs/js-client';
// Functions
export const test_script = `
(xor
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(xor
(call -relay- ("op" "noop") [])
(fail :error:)
)
)
(call %init_peer_id% ("callbackSrv" "response") [])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export type TestParams = [config?: {ttl?: number}] | [peer: IFluenceClient$$, config?: {ttl?: number}];
export type TestResult = Promise<void>;
export function test(...args: TestParams): TestResult {
return callFunction$$(
args,
{
"functionName": "test",
"arrow": {
"domain": {
"fields": {},
"tag": "labeledProduct"
},
"codomain": {
"tag": "nil"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
test_script
);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,114 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Fluence, type ClientConfig } from "@fluencelabs/js-client";
import { test as particleTest } from "./_aqua/finalize_particle.js";
import {
registerHelloWorld,
helloTest,
marineTest,
} from "./_aqua/smoke_test.js";
import { wasm } from "./wasmb64.js";
const relay = {
multiaddr:
"/ip4/127.0.0.1/tcp/9991/ws/p2p/12D3KooWBM3SdXWqGaawQDGQ6JprtwswEg3FWGvGhmgmMez1vRbR",
peerId: "12D3KooWBM3SdXWqGaawQDGQ6JprtwswEg3FWGvGhmgmMez1vRbR",
};
function generateRandomUint8Array() {
const uint8Array = new Uint8Array(32);
for (let i = 0; i < uint8Array.length; i++) {
uint8Array[i] = Math.floor(Math.random() * 256);
}
return uint8Array;
}
const optsWithRandomKeyPair = (): ClientConfig => {
return {
keyPair: {
type: "Ed25519",
source: generateRandomUint8Array(),
},
} as const;
};
export type TestResult =
| { type: "success"; data: string }
| { type: "failure"; error: string };
export const runTest = async (): Promise<TestResult> => {
try {
console.log("connecting to Fluence Network...");
console.log("multiaddr: ", relay.multiaddr);
await Fluence.connect(relay, {
...optsWithRandomKeyPair(),
CDNUrl: "http://localhost:3001",
});
console.log("connected");
const relayPeerId = Fluence.getClient().getRelayPeerId();
console.log("relay:", relayPeerId);
registerHelloWorld({
hello(str) {
return "Hello, " + str + "!";
},
});
const client = Fluence.getClient();
console.log("my peer id: ", client.getPeerId());
console.log("running hello test...");
const hello = await helloTest();
console.log("hello test finished, result: ", hello);
console.log("running marine test...");
const marine = await marineTest(wasm);
console.log("marine test finished, result: ", marine);
console.log("running particle test...");
await particleTest();
const returnVal = {
hello,
marine,
};
return { type: "success", data: JSON.stringify(returnVal) };
} finally {
console.log("disconnecting from Fluence Network...");
await Fluence.disconnect();
console.log("disconnected");
}
};
export const runMain = () => {
runTest()
.then(() => {
console.log("done!");
})
.catch((err) => {
console.error("error: ", err);
});
};

File diff suppressed because one or more lines are too long

View File

@ -1,9 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"module": "NodeNext"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

View File

@ -1,23 +0,0 @@
{
"name": "@test/smoke",
"version": "0.1.0",
"description": "Smoke test",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"type": "module",
"scripts": {
"build": "tsc",
"test": "node --loader ts-node/esm ./src/index.ts"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/js-client": "workspace:*",
"@test/aqua_for_test": "workspace:*"
}
}

View File

@ -1,7 +0,0 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"exclude": ["node_modules", "dist"]
}

View File

@ -1 +0,0 @@
build/

View File

@ -1,46 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View File

@ -1,50 +0,0 @@
{
"name": "cra-ts",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"@test/aqua_for_test": "workspace:*",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "13.5.0",
"@types/jest": "27.5.2",
"@types/node": "16.18.12",
"@types/react": "18.0.27",
"@types/react-dom": "18.0.10",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "2.1.4"
},
"devDependencies": {
"@test/test-utils": "workspace:*",
"puppeteer": "19.7.2"
},
"scripts": {
"test": "node --loader ts-node/esm ./test/index.ts",
"simulate-cdn": "http-server -p 8766 ../../../client/js-client.web.standalone/dist",
"start": "react-scripts start",
"build": "react-scripts build",
"_test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -1,38 +0,0 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@ -1,9 +0,0 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@ -1,61 +0,0 @@
import { runTest, TestResult } from "@test/aqua_for_test";
import React from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
const [result, setResult] = React.useState<TestResult | null>(null);
const onButtonClick = () => {
runTest()
.then((res) => {
setResult(res);
})
.catch((err) => {
if (err instanceof Error) {
console.log(
JSON.stringify({
name: err.name,
message: err.message,
stack: err.stack,
}),
);
} else {
console.log(JSON.stringify(err));
}
setResult({ type: "failure", error: err.toString() });
});
};
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<button id="btn" onClick={onButtonClick}>
Click to run test
</button>
{result && result.type === "success" && (
<div id="res">{result.data}</div>
)}
{result && result.type === "failure" && (
<div id="error">{result.error}</div>
)}
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

View File

@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

View File

@ -1,19 +0,0 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement,
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -1 +0,0 @@
/// <reference types="react-scripts" />

View File

@ -1,15 +0,0 @@
import { ReportHandler } from "web-vitals";
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import("web-vitals").then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -1,5 +0,0 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom";

View File

@ -1,62 +0,0 @@
import puppeteer from "puppeteer";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import {
CDN_PUBLIC_PATH,
createSymlinkIfNotExists,
JS_CLIENT_DEPS_PATH,
startContentServer,
stopServer,
} from "@test/test-utils";
const port = 3001;
const uri = `http://localhost:${port}/`;
const __dirname = dirname(fileURLToPath(import.meta.url));
const publicPath = join(__dirname, "../build/");
const test = async () => {
const localServer = await startContentServer(port, publicPath);
await createSymlinkIfNotExists(
JS_CLIENT_DEPS_PATH,
join(publicPath, "node_modules"),
);
console.log("starting puppeteer...");
const browser = await puppeteer.launch();
const page = (await browser.pages())[0];
page.on("console", (message) =>
console.log(`${message.type().toUpperCase()}: ${message.text()}`),
);
page.on("request", (request) => {
console.log(`INFO: ${request.url()} ${request.method()}`);
});
page.on("requestfailed", (request) => {
console.log(`ERROR: ${request.url()} ${request.failure()?.errorText}`);
});
console.log("going to the page in browser...");
await page.goto(uri);
console.log("clicking button...");
await page.click("#btn");
console.log("waiting for result to appear...");
const elem = await page.waitForSelector("#res");
console.log("getting the content of result div...");
const content = await elem?.evaluate((x) => x.textContent);
console.log("raw result: ", content);
await browser.close();
await stopServer(localServer);
if (!content) {
throw new Error("smoke test failed!");
}
};
test().then(() => console.log("smoke tests succeed!"));

View File

@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src", "test"]
}

View File

@ -1,28 +0,0 @@
{
"name": "@tests/smoke_web",
"version": "0.1.0",
"description": "Smoke test web",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"type": "module",
"scripts": {
"build": "tsc",
"simulate-cdn": "http-server -p 8765 ../../../client/js-client.web.standalone/dist",
"test": "node --loader ts-node/esm ./src/index.ts",
"serve": "http-server public"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/js-client-isomorphic": "workspace:*",
"@test/test-utils": "workspace:*"
},
"devDependencies": {
"puppeteer": "19.7.2"
}
}

View File

@ -1,25 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Smoke test for web</title>
</head>
<body>
<main>
<h1>Open console f12</h1>
<button id="btn">Click to run test</button>
<div id="res-placeholder"></div>
<!-- Importing js-client from local server that is used instead of the CDN -->
<script type="module" src="js-client.min.js"></script>
<script type="module" src="index.js"></script>
</main>
</body>
</html>

View File

@ -1,120 +0,0 @@
import { Fluence, callAquaFunction, randomStage } from "./js-client.min.js";
const relay = {
multiaddr:
"/ip4/127.0.0.1/tcp/9991/ws/p2p/12D3KooWBM3SdXWqGaawQDGQ6JprtwswEg3FWGvGhmgmMez1vRbR",
peerId: "12D3KooWBM3SdXWqGaawQDGQ6JprtwswEg3FWGvGhmgmMez1vRbR",
};
const getRelayTime = () => {
const script = `
(xor
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "relayPeerId") [] relayPeerId)
)
(call -relay- ("op" "noop") [])
)
(xor
(seq
(call relayPeerId ("peer" "timestamp_ms") [] ts)
(call -relay- ("op" "noop") [])
)
(seq
(call -relay- ("op" "noop") [])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1])
)
)
)
(xor
(call %init_peer_id% ("callbackSrv" "response") [ts])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2])
)
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3])
)`;
const def = {
functionName: "getRelayTime",
arrow: {
tag: "arrow",
domain: {
tag: "labeledProduct",
fields: {
relayPeerId: {
tag: "scalar",
name: "string",
},
},
},
codomain: {
tag: "unlabeledProduct",
items: [
{
tag: "scalar",
name: "u64",
},
],
},
},
names: {
relay: "-relay-",
getDataSrv: "getDataSrv",
callbackSrv: "callbackSrv",
responseSrv: "callbackSrv",
responseFnName: "response",
errorHandlingSrv: "errorHandlingSrv",
errorFnName: "error",
},
};
const config = {};
const args = { relayPeerId: relay.peerId };
return callAquaFunction({
args,
script,
config,
peer: Fluence.defaultClient,
fireAndForget: false
});
};
const main = async () => {
console.log("starting fluence...");
await Fluence.connect(relay, {
CDNUrl: "http://localhost:3000",
});
console.log("started fluence");
console.log("getting relay time...");
const relayTime = await getRelayTime();
console.log("got relay time, ", relayTime);
console.log("stopping fluence...");
await Fluence.disconnect();
console.log("stopped fluence...");
return relayTime;
};
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
main().then((res) => {
const inner = document.createElement("div");
inner.id = "res";
inner.innerText = res;
document.getElementById("res-placeholder").appendChild(inner);
}).catch(err => {
if (err instanceof Error) {
console.log(JSON.stringify({ name: err.name, message: err.message, stack: err.stack }));
return;
}
console.log(JSON.stringify(err));
});
});

View File

@ -1,90 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import assert from "node:assert";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import {
CDN_PUBLIC_PATH,
createSymlinkIfNotExists,
JS_CLIENT_DEPS_PATH,
startContentServer,
stopServer,
} from "@test/test-utils";
import puppeteer from "puppeteer";
const port = 3000;
const uri = `http://localhost:${port}/`;
const __dirname = dirname(fileURLToPath(import.meta.url));
const publicPath = join(__dirname, "../public/");
const test = async () => {
const localServer = await startContentServer(port, publicPath);
await createSymlinkIfNotExists(CDN_PUBLIC_PATH, join(publicPath, "source"));
await createSymlinkIfNotExists(
JS_CLIENT_DEPS_PATH,
join(publicPath, "node_modules"),
);
console.log("starting puppeteer...");
const browser = await puppeteer.launch();
const page = (await browser.pages())[0];
assert(page);
page.on("console", (message) => {
console.log(`${message.type().toUpperCase()}: ${message.text()}`);
});
page.on("request", (request) => {
console.log(`INFO: ${request.url()} ${request.method()}`);
});
page.on("requestfailed", (request) => {
console.log(`ERROR: ${request.url()} ${request.failure()?.errorText}`);
});
console.log("going to the page in browser...");
await page.goto(uri);
console.log("clicking button...");
await page.click("#btn");
console.log("waiting for result to appear...");
const elem = await page.waitForSelector("#res");
console.log("getting the content of result div...");
const content = await elem?.evaluate((x) => {
return x.textContent;
});
console.log("raw result: ", content);
await browser.close();
await stopServer(localServer);
if (content === null || content === undefined) {
throw new Error("smoke test failed!");
}
};
void test().then(() => {
console.log("smoke tests succeed!");
});

View File

@ -1,7 +0,0 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"exclude": ["node_modules", "dist", "public"]
}

View File

@ -1,24 +0,0 @@
{
"name": "@test/test-utils",
"version": "0.1.0",
"description": "Test utils",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"type": "module",
"scripts": {
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"serve-handler": "6.1.5"
},
"devDependencies": {
"@types/serve-handler": "6.1.1"
}
}

View File

@ -1,110 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { access, symlink } from "fs/promises";
import { createServer } from "http";
import type { Server } from "http";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import handler from "serve-handler";
const __dirname = dirname(fileURLToPath(import.meta.url));
export const CDN_PUBLIC_PATH = join(
__dirname,
"../../../core/js-client/dist/browser",
);
export const JS_CLIENT_DEPS_PATH = join(
__dirname,
"../../../core/js-client/node_modules",
);
export const startCdn = (port: number) => {
return startContentServer(port, CDN_PUBLIC_PATH);
};
export const createSymlinkIfNotExists = async (
target: string,
path: string,
) => {
try {
await access(path);
} catch {
await symlink(target, path);
}
};
export const startContentServer = (
port: number,
publicDir: string,
): Promise<Server> => {
const server = createServer((request, response) => {
void handler(request, response, {
public: publicDir,
rewrites: [
{
source: "/js-client.min.js",
destination: "/source/index.min.js",
},
{
source: "/@fluencelabs/:name([\\w-]+)@:version([\\w-.]+)/dist/:asset",
destination:
"/node_modules/@fluencelabs/js-client-isomorphic/node_modules/@fluencelabs/:name/dist/:asset",
},
{
source:
"/@fluencelabs/:name([\\w-]+)@:version([\\w-.]+)/dist/:prefix/:asset",
destination:
"/node_modules/@fluencelabs/js-client-isomorphic/node_modules/@fluencelabs/:name/dist/:prefix/:asset",
},
],
headers: [
{
source: "**/*",
headers: [
{
key: "Cross-Origin-Opener-Policy",
value: "same-origin",
},
{
key: "Cross-Origin-Embedder-Policy",
value: "require-corp",
},
],
},
],
});
});
return new Promise<Server>((resolve) => {
const result = server.listen(port, () => {
console.log(`server started on port ${port}`);
console.log(`public dir ${publicDir}`);
resolve(result);
});
});
};
export const stopServer = (app: Server): Promise<void> => {
return new Promise<void>((resolve) => {
app.close(() => {
console.log("server stopped");
resolve();
});
});
};

View File

@ -1,8 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}

View File

@ -1,3 +0,0 @@
{
"ignorePatterns": ["src/**/__snapshots__/**/*", "src/**/*.js"]
}

View File

@ -1,162 +0,0 @@
# Changelog
### Dependencies
- The following workspace dependencies were updated
- devDependencies
- @fluencelabs/js-client bumped to 0.1.7
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.2.0
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.2.1
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.5.1
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/interfaces bumped to 0.9.0
* @fluencelabs/js-client bumped to 0.5.2
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.5.3
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.5.4
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/interfaces bumped to 0.10.0
* @fluencelabs/js-client bumped to 0.6.0
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/interfaces bumped to 0.11.0
* @fluencelabs/js-client bumped to 0.7.0
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.8.0
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.8.1
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.8.2
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.8.3
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.8.4
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/interfaces bumped to 0.12.0
* @fluencelabs/js-client bumped to 0.9.0
## [0.3.5](https://github.com/fluencelabs/js-client/compare/aqua-to-js-v0.3.4...aqua-to-js-v0.3.5) (2023-12-15)
### Features
* **npm-aqua-compiler:** create package ([#401](https://github.com/fluencelabs/js-client/issues/401)) ([d600811](https://github.com/fluencelabs/js-client/commit/d6008110cf0ecaf23a63cfef0bb3f786a6eb0937))
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.5.5
## [0.3.0](https://github.com/fluencelabs/js-client/compare/aqua-to-js-v0.2.0...aqua-to-js-v0.3.0) (2023-11-22)
### ⚠ BREAKING CHANGES
* **js-client:** Segregation of responsibility between js-client packages [fixes DXJ-525] ([#378](https://github.com/fluencelabs/js-client/issues/378))
### Features
* **js-client:** Segregation of responsibility between js-client packages [fixes DXJ-525] ([#378](https://github.com/fluencelabs/js-client/issues/378)) ([f4a550d](https://github.com/fluencelabs/js-client/commit/f4a550dd226846dfc2ade1ccc35a286dc3be2fed))
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.5.0
## [0.2.0](https://github.com/fluencelabs/js-client/compare/aqua-to-js-v0.1.0...aqua-to-js-v0.2.0) (2023-10-25)
### ⚠ BREAKING CHANGES
* **js-client:** Simplify/optimize js-client and update README [fixes DXJ-490] ([#366](https://github.com/fluencelabs/js-client/issues/366))
### Miscellaneous Chores
* **js-client:** Simplify/optimize js-client and update README [fixes DXJ-490] ([#366](https://github.com/fluencelabs/js-client/issues/366)) ([f9abc64](https://github.com/fluencelabs/js-client/commit/f9abc6419c9b32aacec4b05a625d08ec7ff407ba))
## [0.1.0](https://github.com/fluencelabs/js-client/compare/aqua-to-js-v0.0.4...aqua-to-js-v0.1.0) (2023-10-18)
### ⚠ BREAKING CHANGES
* **js-client:** Adding strictes eslint and ts config to all packages [fixes DXJ-464] ([#355](https://github.com/fluencelabs/js-client/issues/355))
### Features
* **js-client:** Adding strictes eslint and ts config to all packages [fixes DXJ-464] ([#355](https://github.com/fluencelabs/js-client/issues/355)) ([919c7d6](https://github.com/fluencelabs/js-client/commit/919c7d6ea1e9c153ff7a367873c85fb36624125d))
### Dependencies
* The following workspace dependencies were updated
* devDependencies
* @fluencelabs/js-client bumped to 0.3.0
## 0.0.1 (2023-09-22)
### Features
- **aqua-compiler:** JS-client aqua wrapper [fixes DXJ-461] ([#347](https://github.com/fluencelabs/js-client/issues/347)) ([7fff3b1](https://github.com/fluencelabs/js-client/commit/7fff3b1c0374eef76ab4e665b13cf97b5c50ff70))

View File

@ -1,31 +0,0 @@
{
"name": "@fluencelabs/aqua-to-js",
"type": "module",
"version": "0.3.13",
"description": "Tool for generating aqua wrapper",
"main": "dist/index.js",
"files": [
"dist"
],
"scripts": {
"test": "vitest run",
"build": "tsc"
},
"keywords": [],
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"ts-pattern": "5.0.5"
},
"devDependencies": {
"@fluencelabs/aqua-api": "0.13.0",
"@fluencelabs/aqua-lib": "0.7.3",
"@fluencelabs/interfaces": "workspace:*",
"@fluencelabs/js-client": "workspace:^",
"@fluencelabs/registry": "0.9.0",
"@fluencelabs/spell": "0.5.20",
"@fluencelabs/trust-graph": "0.4.7",
"vitest": "0.34.6",
"zod": "3.22.4"
}
}

View File

@ -1,140 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ArrowType, NonArrowType } from "@fluencelabs/interfaces";
import { match, P } from "ts-pattern";
import { getFuncArgs } from "./utils.js";
export function genTypeName(
t: NonArrowType | ArrowType,
name: string,
): readonly [string | undefined, string] {
const genType = typeToTs(t);
return match(t)
.with({ tag: "nil" }, () => {
return [undefined, "void"] as const;
})
.with({ tag: "struct" }, () => {
return [`export type ${name} = ${genType}`, name] as const;
})
.with({ tag: P.union("labeledProduct", "unlabeledProduct") }, (item) => {
const args =
item.tag === "labeledProduct" ? Object.values(item.fields) : item.items;
if (args.length === 1 && "0" in args) {
return genTypeName(args[0], name);
}
return [`export type ${name} = ${genType}`, name] as const;
})
.otherwise(() => {
return [undefined, genType] as const;
});
}
export function typeToTs(t: NonArrowType | ArrowType): string {
return match(t)
.with({ tag: "nil" }, () => {
return "null";
})
.with({ tag: "option" }, ({ type }) => {
return typeToTs(type) + " | null";
})
.with({ tag: "scalar" }, ({ name }) => {
return match(name)
.with(
P.union(
"u8",
"u16",
"u32",
"u64",
"i8",
"i16",
"i32",
"i64",
"f32",
"f64",
),
() => {
return "number";
},
)
.with("bool", () => {
return "boolean";
})
.with("string", () => {
return "string";
})
.with(P._, () => {
return "any";
})
.exhaustive();
})
.with({ tag: "array" }, ({ type }) => {
return typeToTs(type) + "[]";
})
.with({ tag: "struct" }, ({ fields }) => {
return `{ ${Object.entries(fields)
.map(([field, type]) => {
return `${field}: ${typeToTs(type)};`;
})
.join(" ")} }`;
})
.with({ tag: "labeledProduct" }, ({ fields }) => {
return `{ ${Object.entries(fields)
.map(([field, type]) => {
return `${field}: ${typeToTs(type)};`;
})
.join(" ")} }`;
})
.with({ tag: "unlabeledProduct" }, ({ items }) => {
return `[${items
.map((item) => {
return typeToTs(item);
})
.join(", ")}]`;
})
.with({ tag: "arrow" }, ({ domain, codomain }) => {
const retType =
codomain.tag === "nil"
? "void"
: codomain.items.length === 1 && "0" in codomain.items
? typeToTs(codomain.items[0])
: typeToTs(codomain);
const args = getFuncArgs(domain).map(([name, type]) => {
return [name, typeToTs(type)];
});
args.push(["callParams", `ParticleContext$$`]);
const funcArgs = args
.map(([name, type]) => {
return `${name}: ${type}`;
})
.join(", ");
return `(${funcArgs}) => ${retType} | Promise<${retType}>`;
})
.with({ tag: "topType" }, () => {
return "unknown";
})
.with({ tag: "bottomType" }, () => {
return "never";
})
.exhaustive();
}

View File

@ -1,67 +0,0 @@
/* eslint-disable */
// @ts-nocheck
/**
*
* This file is generated using:
* @fluencelabs/aqua-api version: 0.0.0
* @fluencelabs/aqua-to-js version: 0.0.0
* If you find any bugs in generated AIR, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* If you find any bugs in generated JS/TS, please write an issue on GitHub: https://github.com/fluencelabs/js-client/issues
*
*/
import type { IFluenceClient as IFluenceClient$$, ParticleContext as ParticleContext$$ } from '@fluencelabs/js-client';
// Making aliases to reduce chance of accidental name collision
import {
v5_callFunction as callFunction$$,
v5_registerService as registerService$$
} from '@fluencelabs/js-client';
// Services
export interface SrvDef {
create: (wasm_b64_content: string, callParams: ParticleContext$$) => { error: string | null; service_id: string | null; success: boolean; } | Promise<{ error: string | null; service_id: string | null; success: boolean; }>;
list: (callParams: ParticleContext$$) => string[] | Promise<string[]>;
remove: (service_id: string, callParams: ParticleContext$$) => { error: string | null; success: boolean; } | Promise<{ error: string | null; success: boolean; }>;
}
export function registerSrv(service: SrvDef): void;
export function registerSrv(serviceId: string, service: SrvDef): void;
export function registerSrv(peer: IFluenceClient$$, service: SrvDef): void;
export function registerSrv(peer: IFluenceClient$$, serviceId: string, service: SrvDef): void;
export interface CalcServiceDef {
divide: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
clear_state: (callParams: ParticleContext$$) => void | Promise<void>;
test_logs: (callParams: ParticleContext$$) => void | Promise<void>;
multiply: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
add: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
state: (callParams: ParticleContext$$) => number | Promise<number>;
subtract: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
}
export function registerCalcService(serviceId: string, service: CalcServiceDef): void;
export function registerCalcService(peer: IFluenceClient$$, serviceId: string, service: CalcServiceDef): void;
export interface HelloWorldDef {
hello: (str: string, callParams: ParticleContext$$) => string | Promise<string>;
}
export function registerHelloWorld(service: HelloWorldDef): void;
export function registerHelloWorld(serviceId: string, service: HelloWorldDef): void;
export function registerHelloWorld(peer: IFluenceClient$$, service: HelloWorldDef): void;
export function registerHelloWorld(peer: IFluenceClient$$, serviceId: string, service: HelloWorldDef): void;
// Functions
export type ResourceTestResultType = [string | null, string[]]
export type ResourceTestParams = [label: string, config?: {ttl?: number}] | [peer: IFluenceClient$$, label: string, config?: {ttl?: number}];
export type ResourceTestResult = Promise<ResourceTestResultType>;
export type HelloTestParams = [config?: {ttl?: number}] | [peer: IFluenceClient$$, config?: {ttl?: number}];
export type HelloTestResult = Promise<string>;
export type Demo_calculationParams = [service_id: string, config?: {ttl?: number}] | [peer: IFluenceClient$$, service_id: string, config?: {ttl?: number}];
export type Demo_calculationResult = Promise<number>;
export type MarineTestParams = [wasm64: string, config?: {ttl?: number}] | [peer: IFluenceClient$$, wasm64: string, config?: {ttl?: number}];
export type MarineTestResult = Promise<number>;

View File

@ -1,900 +0,0 @@
/* eslint-disable */
// @ts-nocheck
/**
*
* This file is generated using:
* @fluencelabs/aqua-api version: 0.0.0
* @fluencelabs/aqua-to-js version: 0.0.0
* If you find any bugs in generated AIR, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* If you find any bugs in generated JS/TS, please write an issue on GitHub: https://github.com/fluencelabs/js-client/issues
*
*/
// Making aliases to reduce chance of accidental name collision
import {
v5_callFunction as callFunction$$,
v5_registerService as registerService$$
} from '@fluencelabs/js-client';
// Services
export function registerSrv(...args) {
registerService$$(
args,
{
"defaultServiceId": "single_module_srv",
"functions": {
"fields": {
"create": {
"domain": {
"fields": {
"wasm_b64_content": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "ServiceCreationResult",
"fields": {
"error": {
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
"service_id": {
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
"success": {
"name": "bool",
"tag": "scalar"
}
},
"tag": "struct"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"list": {
"domain": {
"tag": "nil"
},
"codomain": {
"items": [
{
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "array"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"remove": {
"domain": {
"fields": {
"service_id": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "RemoveResult",
"fields": {
"error": {
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
"success": {
"name": "bool",
"tag": "scalar"
}
},
"tag": "struct"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
}
},
"tag": "labeledProduct"
}
}
);
}
export function registerCalcService(...args) {
registerService$$(
args,
{
"functions": {
"fields": {
"divide": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"clear_state": {
"domain": {
"tag": "nil"
},
"codomain": {
"tag": "nil"
},
"tag": "arrow"
},
"test_logs": {
"domain": {
"tag": "nil"
},
"codomain": {
"tag": "nil"
},
"tag": "arrow"
},
"multiply": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"add": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"state": {
"domain": {
"tag": "nil"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"subtract": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
}
},
"tag": "labeledProduct"
}
}
);
}
export function registerHelloWorld(...args) {
registerService$$(
args,
{
"defaultServiceId": "hello-world",
"functions": {
"fields": {
"hello": {
"domain": {
"fields": {
"str": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "string",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
}
},
"tag": "labeledProduct"
}
}
);
}
// Functions
export const resourceTest_script = `
(xor
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "label") [] -label-arg-)
)
(new $resource_id
(seq
(seq
(seq
(call %init_peer_id% ("peer" "timestamp_sec") [] ret)
(xor
(seq
(seq
(call -relay- ("registry" "get_key_bytes") [-label-arg- [] ret [] ""] ret-0)
(xor
(call %init_peer_id% ("sig" "sign") [ret-0] ret-1)
(fail :error:)
)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(match ret-1.$.success false
(ap ret-1.$.error.[0] $error)
)
(seq
(ap :error: -if-error-)
(xor
(match :error:.$.error_code 10001
(new $successful
(seq
(seq
(seq
(seq
(seq
(seq
(ap ret-1.$.signature ret-1_flat)
(call -relay- ("registry" "get_key_id") [-label-arg- %init_peer_id%] ret-2)
)
(call -relay- ("op" "string_to_b58") [ret-2] ret-3)
)
(call -relay- ("kad" "neighborhood") [ret-3 [] []] ret-4)
)
(par
(fold ret-4 n-0
(par
(xor
(xor
(seq
(seq
(seq
(call n-0 ("peer" "timestamp_sec") [] ret-5)
(call n-0 ("trust-graph" "get_weight") [%init_peer_id% ret-5] ret-6)
)
(call n-0 ("registry" "register_key") [-label-arg- [] ret [] "" ret-1_flat.$.[0] ret-6 ret-5] ret-7)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(seq
(match ret-7.$.success true
(ap true $successful)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap :error: -if-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap ret-7.$.error $error)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(seq
(seq
(ap :error: -else-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap -else-error- -if-else-error-)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
(fail -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
)
)
)
)
)
(null)
)
(fail :error:)
)
(next n-0)
)
(never)
)
(null)
)
)
(new $status
(new $result-1
(seq
(seq
(seq
(par
(seq
(new $successful_test
(seq
(seq
(fold $successful successful_fold_var
(seq
(seq
(ap successful_fold_var $successful_test)
(canon -relay- $successful_test #successful_iter_canon)
)
(xor
(match #successful_iter_canon.length 1
(null)
)
(next successful_fold_var)
)
)
(never)
)
(canon -relay- $successful_test #successful_result_canon)
)
(ap #successful_result_canon successful_gate)
)
)
(ap "ok" $status)
)
(seq
(call -relay- ("peer" "timeout") [6000 "timeout"] ret-8)
(ap ret-8 $status)
)
)
(new $status_test
(seq
(seq
(fold $status status_fold_var
(seq
(seq
(ap status_fold_var $status_test)
(canon -relay- $status_test #status_iter_canon)
)
(xor
(match #status_iter_canon.length 1
(null)
)
(next status_fold_var)
)
)
(never)
)
(canon -relay- $status_test #status_result_canon)
)
(ap #status_result_canon status_gate)
)
)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(match status_gate.$.[0] "ok"
(ap true $result-1)
)
(seq
(ap :error: -if-error-)
(xor
(match :error:.$.error_code 10001
(ap false $result-1)
)
(seq
(seq
(ap :error: -else-error-)
(xor
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(ap -else-error- -if-else-error-)
)
)
(fail -if-else-error-)
)
)
)
)
)
)
)
)
(new $result-1_test
(seq
(seq
(fold $result-1 result-1_fold_var
(seq
(seq
(ap result-1_fold_var $result-1_test)
(canon -relay- $result-1_test #result-1_iter_canon)
)
(xor
(match #result-1_iter_canon.length 1
(null)
)
(next result-1_fold_var)
)
)
(never)
)
(canon -relay- $result-1_test #result-1_result_canon)
)
(ap #result-1_result_canon result-1_gate)
)
)
)
)
)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(match result-1_gate.$.[0] false
(ap "resource wasn't created: timeout exceeded" $error)
)
(seq
(ap :error: -if-error-)
(xor
(match :error:.$.error_code 10001
(ap ret-2 $resource_id)
)
(seq
(seq
(ap :error: -else-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap -else-error- -if-else-error-)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
(fail -if-else-error-)
)
)
)
)
)
)
)
)
)
)
(seq
(seq
(ap :error: -else-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap -else-error- -if-else-error-)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
(fail -if-else-error-)
)
)
)
)
)
)
)
)
(fail :error:)
)
)
(canon %init_peer_id% $resource_id #-resource_id-fix-0)
)
(ap #-resource_id-fix-0 -resource_id-flat-0)
)
)
)
(canon %init_peer_id% $error #error_canon)
)
(call %init_peer_id% ("callbackSrv" "response") [-resource_id-flat-0 #error_canon])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export function resourceTest(...args) {
return callFunction$$(
args,
{
"functionName": "resourceTest",
"arrow": {
"domain": {
"fields": {
"label": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
{
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "array"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
resourceTest_script
);
}
export const helloTest_script = `
(xor
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("hello-world" "hello") ["Fluence user"] ret)
)
(call %init_peer_id% ("callbackSrv" "response") [ret])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export function helloTest(...args) {
return callFunction$$(
args,
{
"functionName": "helloTest",
"arrow": {
"domain": {
"fields": {},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "string",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
helloTest_script
);
}
export const demo_calculation_script = `
(xor
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "service_id") [] -service_id-arg-)
)
(call %init_peer_id% (-service_id-arg- "test_logs") [])
)
(call %init_peer_id% (-service_id-arg- "add") [10] ret)
)
(call %init_peer_id% (-service_id-arg- "multiply") [5] ret-0)
)
(call %init_peer_id% (-service_id-arg- "subtract") [8] ret-1)
)
(call %init_peer_id% (-service_id-arg- "divide") [6] ret-2)
)
(call %init_peer_id% (-service_id-arg- "state") [] ret-3)
)
(call %init_peer_id% ("callbackSrv" "response") [ret-3])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export function demo_calculation(...args) {
return callFunction$$(
args,
{
"functionName": "demo_calculation",
"arrow": {
"domain": {
"fields": {
"service_id": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
demo_calculation_script
);
}
export const marineTest_script = `
(xor
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "wasm64") [] -wasm64-arg-)
)
(call %init_peer_id% ("single_module_srv" "create") [-wasm64-arg-] ret)
)
(call %init_peer_id% (ret.$.service_id.[0] "test_logs") [])
)
(call %init_peer_id% (ret.$.service_id.[0] "add") [10] ret-0)
)
(call %init_peer_id% (ret.$.service_id.[0] "multiply") [5] ret-1)
)
(call %init_peer_id% (ret.$.service_id.[0] "subtract") [8] ret-2)
)
(call %init_peer_id% (ret.$.service_id.[0] "divide") [6] ret-3)
)
(call %init_peer_id% (ret.$.service_id.[0] "state") [] ret-4)
)
(call %init_peer_id% ("callbackSrv" "response") [ret-4])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export function marineTest(...args) {
return callFunction$$(
args,
{
"functionName": "marineTest",
"arrow": {
"domain": {
"fields": {
"wasm64": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
marineTest_script
);
}

View File

@ -1,938 +0,0 @@
/* eslint-disable */
// @ts-nocheck
/**
*
* This file is generated using:
* @fluencelabs/aqua-api version: 0.0.0
* @fluencelabs/aqua-to-js version: 0.0.0
* If you find any bugs in generated AIR, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* If you find any bugs in generated JS/TS, please write an issue on GitHub: https://github.com/fluencelabs/js-client/issues
*
*/
import type { IFluenceClient as IFluenceClient$$, ParticleContext as ParticleContext$$ } from '@fluencelabs/js-client';
// Making aliases to reduce chance of accidental name collision
import {
v5_callFunction as callFunction$$,
v5_registerService as registerService$$
} from '@fluencelabs/js-client';
// Services
export interface SrvDef {
create: (wasm_b64_content: string, callParams: ParticleContext$$) => { error: string | null; service_id: string | null; success: boolean; } | Promise<{ error: string | null; service_id: string | null; success: boolean; }>;
list: (callParams: ParticleContext$$) => string[] | Promise<string[]>;
remove: (service_id: string, callParams: ParticleContext$$) => { error: string | null; success: boolean; } | Promise<{ error: string | null; success: boolean; }>;
}
export function registerSrv(service: SrvDef): void;
export function registerSrv(serviceId: string, service: SrvDef): void;
export function registerSrv(peer: IFluenceClient$$, service: SrvDef): void;
export function registerSrv(peer: IFluenceClient$$, serviceId: string, service: SrvDef): void;
export function registerSrv(...args: any[]) {
registerService$$(
args,
{
"defaultServiceId": "single_module_srv",
"functions": {
"fields": {
"create": {
"domain": {
"fields": {
"wasm_b64_content": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "ServiceCreationResult",
"fields": {
"error": {
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
"service_id": {
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
"success": {
"name": "bool",
"tag": "scalar"
}
},
"tag": "struct"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"list": {
"domain": {
"tag": "nil"
},
"codomain": {
"items": [
{
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "array"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"remove": {
"domain": {
"fields": {
"service_id": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "RemoveResult",
"fields": {
"error": {
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
"success": {
"name": "bool",
"tag": "scalar"
}
},
"tag": "struct"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
}
},
"tag": "labeledProduct"
}
}
);
}
export interface CalcServiceDef {
divide: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
clear_state: (callParams: ParticleContext$$) => void | Promise<void>;
test_logs: (callParams: ParticleContext$$) => void | Promise<void>;
multiply: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
add: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
state: (callParams: ParticleContext$$) => number | Promise<number>;
subtract: (num: number, callParams: ParticleContext$$) => number | Promise<number>;
}
export function registerCalcService(serviceId: string, service: CalcServiceDef): void;
export function registerCalcService(peer: IFluenceClient$$, serviceId: string, service: CalcServiceDef): void;
export function registerCalcService(...args: any[]) {
registerService$$(
args,
{
"functions": {
"fields": {
"divide": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"clear_state": {
"domain": {
"tag": "nil"
},
"codomain": {
"tag": "nil"
},
"tag": "arrow"
},
"test_logs": {
"domain": {
"tag": "nil"
},
"codomain": {
"tag": "nil"
},
"tag": "arrow"
},
"multiply": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"add": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"state": {
"domain": {
"tag": "nil"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"subtract": {
"domain": {
"fields": {
"num": {
"name": "f64",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
}
},
"tag": "labeledProduct"
}
}
);
}
export interface HelloWorldDef {
hello: (str: string, callParams: ParticleContext$$) => string | Promise<string>;
}
export function registerHelloWorld(service: HelloWorldDef): void;
export function registerHelloWorld(serviceId: string, service: HelloWorldDef): void;
export function registerHelloWorld(peer: IFluenceClient$$, service: HelloWorldDef): void;
export function registerHelloWorld(peer: IFluenceClient$$, serviceId: string, service: HelloWorldDef): void;
export function registerHelloWorld(...args: any[]) {
registerService$$(
args,
{
"defaultServiceId": "hello-world",
"functions": {
"fields": {
"hello": {
"domain": {
"fields": {
"str": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "string",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
}
},
"tag": "labeledProduct"
}
}
);
}
// Functions
export const resourceTest_script = `
(xor
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "label") [] -label-arg-)
)
(new $resource_id
(seq
(seq
(seq
(call %init_peer_id% ("peer" "timestamp_sec") [] ret)
(xor
(seq
(seq
(call -relay- ("registry" "get_key_bytes") [-label-arg- [] ret [] ""] ret-0)
(xor
(call %init_peer_id% ("sig" "sign") [ret-0] ret-1)
(fail :error:)
)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(match ret-1.$.success false
(ap ret-1.$.error.[0] $error)
)
(seq
(ap :error: -if-error-)
(xor
(match :error:.$.error_code 10001
(new $successful
(seq
(seq
(seq
(seq
(seq
(seq
(ap ret-1.$.signature ret-1_flat)
(call -relay- ("registry" "get_key_id") [-label-arg- %init_peer_id%] ret-2)
)
(call -relay- ("op" "string_to_b58") [ret-2] ret-3)
)
(call -relay- ("kad" "neighborhood") [ret-3 [] []] ret-4)
)
(par
(fold ret-4 n-0
(par
(xor
(xor
(seq
(seq
(seq
(call n-0 ("peer" "timestamp_sec") [] ret-5)
(call n-0 ("trust-graph" "get_weight") [%init_peer_id% ret-5] ret-6)
)
(call n-0 ("registry" "register_key") [-label-arg- [] ret [] "" ret-1_flat.$.[0] ret-6 ret-5] ret-7)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(seq
(match ret-7.$.success true
(ap true $successful)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap :error: -if-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap ret-7.$.error $error)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(seq
(seq
(ap :error: -else-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap -else-error- -if-else-error-)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
(fail -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
)
)
)
)
)
(null)
)
(fail :error:)
)
(next n-0)
)
(never)
)
(null)
)
)
(new $status
(new $result-1
(seq
(seq
(seq
(par
(seq
(new $successful_test
(seq
(seq
(fold $successful successful_fold_var
(seq
(seq
(ap successful_fold_var $successful_test)
(canon -relay- $successful_test #successful_iter_canon)
)
(xor
(match #successful_iter_canon.length 1
(null)
)
(next successful_fold_var)
)
)
(never)
)
(canon -relay- $successful_test #successful_result_canon)
)
(ap #successful_result_canon successful_gate)
)
)
(ap "ok" $status)
)
(seq
(call -relay- ("peer" "timeout") [6000 "timeout"] ret-8)
(ap ret-8 $status)
)
)
(new $status_test
(seq
(seq
(fold $status status_fold_var
(seq
(seq
(ap status_fold_var $status_test)
(canon -relay- $status_test #status_iter_canon)
)
(xor
(match #status_iter_canon.length 1
(null)
)
(next status_fold_var)
)
)
(never)
)
(canon -relay- $status_test #status_result_canon)
)
(ap #status_result_canon status_gate)
)
)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(match status_gate.$.[0] "ok"
(ap true $result-1)
)
(seq
(ap :error: -if-error-)
(xor
(match :error:.$.error_code 10001
(ap false $result-1)
)
(seq
(seq
(ap :error: -else-error-)
(xor
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(ap -else-error- -if-else-error-)
)
)
(fail -if-else-error-)
)
)
)
)
)
)
)
)
(new $result-1_test
(seq
(seq
(fold $result-1 result-1_fold_var
(seq
(seq
(ap result-1_fold_var $result-1_test)
(canon -relay- $result-1_test #result-1_iter_canon)
)
(xor
(match #result-1_iter_canon.length 1
(null)
)
(next result-1_fold_var)
)
)
(never)
)
(canon -relay- $result-1_test #result-1_result_canon)
)
(ap #result-1_result_canon result-1_gate)
)
)
)
)
)
)
(new -if-else-error-
(new -else-error-
(new -if-error-
(xor
(match result-1_gate.$.[0] false
(ap "resource wasn't created: timeout exceeded" $error)
)
(seq
(ap :error: -if-error-)
(xor
(match :error:.$.error_code 10001
(ap ret-2 $resource_id)
)
(seq
(seq
(ap :error: -else-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap -else-error- -if-else-error-)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
(fail -if-else-error-)
)
)
)
)
)
)
)
)
)
)
(seq
(seq
(ap :error: -else-error-)
(xor
(seq
(match :error:.$.error_code 10001
(ap -if-error- -if-else-error-)
)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
(seq
(ap -else-error- -if-else-error-)
(new $-ephemeral-stream-
(new #-ephemeral-canon-
(canon -relay- $-ephemeral-stream- #-ephemeral-canon-)
)
)
)
)
)
(fail -if-else-error-)
)
)
)
)
)
)
)
)
(fail :error:)
)
)
(canon %init_peer_id% $resource_id #-resource_id-fix-0)
)
(ap #-resource_id-fix-0 -resource_id-flat-0)
)
)
)
(canon %init_peer_id% $error #error_canon)
)
(call %init_peer_id% ("callbackSrv" "response") [-resource_id-flat-0 #error_canon])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export type ResourceTestResultType = [string | null, string[]]
export type ResourceTestParams = [label: string, config?: {ttl?: number}] | [peer: IFluenceClient$$, label: string, config?: {ttl?: number}];
export type ResourceTestResult = Promise<ResourceTestResultType>;
export function resourceTest(...args: ResourceTestParams): ResourceTestResult {
return callFunction$$(
args,
{
"functionName": "resourceTest",
"arrow": {
"domain": {
"fields": {
"label": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "option"
},
{
"type": {
"name": "string",
"tag": "scalar"
},
"tag": "array"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
resourceTest_script
);
}
export const helloTest_script = `
(xor
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("hello-world" "hello") ["Fluence user"] ret)
)
(call %init_peer_id% ("callbackSrv" "response") [ret])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export type HelloTestParams = [config?: {ttl?: number}] | [peer: IFluenceClient$$, config?: {ttl?: number}];
export type HelloTestResult = Promise<string>;
export function helloTest(...args: HelloTestParams): HelloTestResult {
return callFunction$$(
args,
{
"functionName": "helloTest",
"arrow": {
"domain": {
"fields": {},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "string",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
helloTest_script
);
}
export const demo_calculation_script = `
(xor
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "service_id") [] -service_id-arg-)
)
(call %init_peer_id% (-service_id-arg- "test_logs") [])
)
(call %init_peer_id% (-service_id-arg- "add") [10] ret)
)
(call %init_peer_id% (-service_id-arg- "multiply") [5] ret-0)
)
(call %init_peer_id% (-service_id-arg- "subtract") [8] ret-1)
)
(call %init_peer_id% (-service_id-arg- "divide") [6] ret-2)
)
(call %init_peer_id% (-service_id-arg- "state") [] ret-3)
)
(call %init_peer_id% ("callbackSrv" "response") [ret-3])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export type Demo_calculationParams = [service_id: string, config?: {ttl?: number}] | [peer: IFluenceClient$$, service_id: string, config?: {ttl?: number}];
export type Demo_calculationResult = Promise<number>;
export function demo_calculation(...args: Demo_calculationParams): Demo_calculationResult {
return callFunction$$(
args,
{
"functionName": "demo_calculation",
"arrow": {
"domain": {
"fields": {
"service_id": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
demo_calculation_script
);
}
export const marineTest_script = `
(xor
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "wasm64") [] -wasm64-arg-)
)
(call %init_peer_id% ("single_module_srv" "create") [-wasm64-arg-] ret)
)
(call %init_peer_id% (ret.$.service_id.[0] "test_logs") [])
)
(call %init_peer_id% (ret.$.service_id.[0] "add") [10] ret-0)
)
(call %init_peer_id% (ret.$.service_id.[0] "multiply") [5] ret-1)
)
(call %init_peer_id% (ret.$.service_id.[0] "subtract") [8] ret-2)
)
(call %init_peer_id% (ret.$.service_id.[0] "divide") [6] ret-3)
)
(call %init_peer_id% (ret.$.service_id.[0] "state") [] ret-4)
)
(call %init_peer_id% ("callbackSrv" "response") [ret-4])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [:error: 0])
)
`;
export type MarineTestParams = [wasm64: string, config?: {ttl?: number}] | [peer: IFluenceClient$$, wasm64: string, config?: {ttl?: number}];
export type MarineTestResult = Promise<number>;
export function marineTest(...args: MarineTestParams): MarineTestResult {
return callFunction$$(
args,
{
"functionName": "marineTest",
"arrow": {
"domain": {
"fields": {
"wasm64": {
"name": "string",
"tag": "scalar"
}
},
"tag": "labeledProduct"
},
"codomain": {
"items": [
{
"name": "f64",
"tag": "scalar"
}
],
"tag": "unlabeledProduct"
},
"tag": "arrow"
},
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
},
marineTest_script
);
}

View File

@ -1,68 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fileURLToPath } from "url";
import { compileFromPath } from "@fluencelabs/aqua-api";
import { beforeAll, describe, expect, it } from "vitest";
import { getPackageJsonContent, PackageJson } from "../../utils.js";
import { generateTypes, generateSources } from "../index.js";
import { CompilationResult } from "../interfaces.js";
let res: Omit<CompilationResult, "funcCall">;
let pkg: PackageJson;
describe("Aqua to js/ts compiler", () => {
beforeAll(async () => {
res = await compileFromPath({
filePath: fileURLToPath(
new URL("./sources/smoke_test.aqua", import.meta.url),
),
imports: ["./node_modules"],
targetType: "air",
});
pkg = {
...(await getPackageJsonContent()),
version: "0.0.0",
devDependencies: {
"@fluencelabs/aqua-api": "0.0.0",
},
};
});
it("matches js snapshots", async () => {
const jsResult = generateSources(res, "js", pkg);
const jsTypes = generateTypes(res, pkg);
await expect(jsResult).toMatchFileSnapshot(
"./__snapshots__/generate.snap.js",
);
await expect(jsTypes).toMatchFileSnapshot(
"./__snapshots__/generate.snap.d.ts",
);
});
it("matches ts snapshots", async () => {
const tsResult = generateSources(res, "ts", pkg);
await expect(tsResult).toMatchFileSnapshot(
"./__snapshots__/generate.snap.ts",
);
});
});

View File

@ -1,55 +0,0 @@
import "@fluencelabs/registry/resources-api.aqua"
service HelloWorld("hello-world"):
hello(str: string) -> string
func resourceTest(label: string) -> ?string, *string:
res, errors <- createResource(label)
<- res, errors
func helloTest() -> string:
hello <- HelloWorld.hello("Fluence user")
<- hello
service CalcService:
add(num: f64) -> f64
clear_state()
divide(num: f64) -> f64
multiply(num: f64) -> f64
state() -> f64
subtract(num: f64) -> f64
test_logs()
data ServiceCreationResult:
success: bool
service_id: ?string
error: ?string
data RemoveResult:
success: bool
error: ?string
alias ListServiceResult: []string
service Srv("single_module_srv"):
create(wasm_b64_content: string) -> ServiceCreationResult
remove(service_id: string) -> RemoveResult
list() -> ListServiceResult
func demo_calculation(service_id: string) -> f64:
CalcService service_id
CalcService.test_logs()
CalcService.add(10)
CalcService.multiply(5)
CalcService.subtract(8)
CalcService.divide(6)
res <- CalcService.state()
<- res
func marineTest(wasm64: string) -> f64:
serviceResult <- Srv.create(wasm64)
res <- demo_calculation(serviceResult.service_id!)
<- res

View File

@ -1,54 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { capitalize, recursiveRenameLaquaProps } from "../utils.js";
import { AquaFunction, TypeGenerator } from "./interfaces.js";
export function generateFunctions(
typeGenerator: TypeGenerator,
functions: Record<string, AquaFunction>,
) {
return Object.values(functions)
.map((func) => {
return generateFunction(typeGenerator, func);
})
.join("\n\n");
}
type DeepToType<T> = { [K in keyof T]: DeepToType<T[K]> };
function generateFunction(typeGenerator: TypeGenerator, func: AquaFunction) {
const funcDef: DeepToType<typeof func.funcDef> = func.funcDef;
const scriptConstName = func.funcDef.functionName + "_script";
return `export const ${scriptConstName} = \`
${func.script}\`;
${typeGenerator.funcType(func)}
export function ${func.funcDef.functionName}(${typeGenerator.type(
"...args",
`${capitalize(func.funcDef.functionName)}Params`,
)})${typeGenerator.type(
"",
`${capitalize(func.funcDef.functionName)}Result`,
)} {
return callFunction$$(
args,
${JSON.stringify(recursiveRenameLaquaProps(funcDef), null, 4)},
${scriptConstName}
);
}`;
}

View File

@ -1,47 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { PackageJson } from "../utils.js";
import { OutputType } from "./interfaces.js";
export default function generateHeader(
{ version, devDependencies }: PackageJson,
outputType: OutputType,
) {
return `/* eslint-disable */
// @ts-nocheck
/**
*
* This file is generated using:
* @fluencelabs/aqua-api version: ${devDependencies["@fluencelabs/aqua-api"]}
* @fluencelabs/aqua-to-js version: ${version}
* If you find any bugs in generated AIR, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* If you find any bugs in generated JS/TS, please write an issue on GitHub: https://github.com/fluencelabs/js-client/issues
*
*/
${
outputType === "ts"
? "import type { IFluenceClient as IFluenceClient$$, ParticleContext as ParticleContext$$ } from '@fluencelabs/js-client';"
: ""
}
// Making aliases to reduce chance of accidental name collision
import {
v5_callFunction as callFunction$$,
v5_registerService as registerService$$
} from '@fluencelabs/js-client';`;
}

View File

@ -1,93 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { PackageJson } from "../utils.js";
import { generateFunctions } from "./function.js";
import header from "./header.js";
import {
CompilationResult,
JSTypeGenerator,
OutputType,
TSTypeGenerator,
TypeGenerator,
} from "./interfaces.js";
import { generateServices } from "./service.js";
const typeGenerators: Record<OutputType, TypeGenerator> = {
js: new JSTypeGenerator(),
ts: new TSTypeGenerator(),
};
export function generateSources(
{ services, functions }: CompilationResult,
outputType: OutputType,
packageJson: PackageJson,
) {
const typeGenerator = typeGenerators[outputType];
return `${header(packageJson, outputType)}
${
Object.entries(services).length > 0
? `// Services
${generateServices(typeGenerator, services)}
`
: ""
}
${
Object.entries(functions).length > 0
? `// Functions
${generateFunctions(typeGenerator, functions)}
`
: ""
}`;
}
export function generateTypes(
{ services, functions }: CompilationResult,
packageJson: PackageJson,
) {
const typeGenerator = typeGenerators["ts"];
const generatedServices = Object.entries(services)
.map(([srvName, srvDef]) => {
return typeGenerator.serviceType(srvName, srvDef);
})
.join("\n");
const generatedFunctions = Object.entries(functions)
.map(([, funcDef]) => {
return typeGenerator.funcType(funcDef);
})
.join("\n");
return `${header(packageJson, "ts")}
${
Object.entries(services).length > 0
? `// Services
${generatedServices}
`
: ""
}
${
Object.entries(functions).length > 0
? `// Functions
${generatedFunctions}
`
: ""
}`;
}

View File

@ -1,185 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FunctionCallDef, ServiceDef } from "@fluencelabs/interfaces";
import { genTypeName, typeToTs } from "../common.js";
import { CLIENT } from "../constants.js";
import { capitalize, getFuncArgs } from "../utils.js";
export interface TypeGenerator {
type(field: string, type: string): string;
generic(field: string, type: string): string;
bang(field: string): string;
funcType(funcDef: AquaFunction): string;
serviceType(srvName: string, srvDef: ServiceDef): string;
}
export class TSTypeGenerator implements TypeGenerator {
bang(field: string): string {
return `${field}!`;
}
generic(field: string, type: string): string {
return `${field}<${type}>`;
}
type(field: string, type: string): string {
return `${field}: ${type}`;
}
funcType({ funcDef }: AquaFunction): string {
const args = getFuncArgs(funcDef.arrow.domain).map(([name, type]) => {
const [typeDesc, t] = genTypeName(
type,
capitalize(funcDef.functionName) + "Arg" + capitalize(name),
);
return [typeDesc, `${name}: ${t}`] as const;
});
args.push([undefined, `config?: {ttl?: number}`]);
const argsDefs = args.map(([, def]) => {
return def;
});
const argsDesc = args
.filter(([desc]) => {
return desc !== undefined;
})
.map(([desc]) => {
return desc;
});
const functionOverloads = [
argsDefs.join(", "),
[`peer: ${CLIENT}`, ...argsDefs].join(", "),
];
const [resTypeDesc, resType] = genTypeName(
funcDef.arrow.codomain,
capitalize(funcDef.functionName) + "ResultType",
);
const functionOverloadArgsType = functionOverloads
.map((overload) => {
return `[${overload}]`;
})
.join(" | ");
return [
argsDesc.join("\n"),
resTypeDesc ?? "",
`export type ${capitalize(
funcDef.functionName,
)}Params = ${functionOverloadArgsType};`,
`export type ${capitalize(
funcDef.functionName,
)}Result = Promise<${resType}>;\n`,
]
.filter((s) => {
return s !== "";
})
.join("\n\n");
}
serviceType(srvName: string, srvDef: ServiceDef): string {
const members =
srvDef.functions.tag === "nil"
? []
: Object.entries(srvDef.functions.fields);
const interfaceDefs = members
.map(([name, arrow]) => {
return ` ${name}: ${typeToTs(arrow)};`;
})
.join("\n");
const interfaces = [
`export interface ${srvName}Def {`,
interfaceDefs,
"}",
].join("\n");
const peerDecl = `peer: ${CLIENT}`;
const serviceDecl = `service: ${srvName}Def`;
const serviceIdDecl = `serviceId: string`;
const functionOverloadsWithDefaultServiceId = [
[serviceDecl],
[serviceIdDecl, serviceDecl],
[peerDecl, serviceDecl],
[peerDecl, serviceIdDecl, serviceDecl],
];
const functionOverloadsWithoutDefaultServiceId = [
[serviceIdDecl, serviceDecl],
[peerDecl, serviceIdDecl, serviceDecl],
];
const registerServiceArgs =
srvDef.defaultServiceId === undefined
? functionOverloadsWithoutDefaultServiceId
: functionOverloadsWithDefaultServiceId;
return [
interfaces,
...registerServiceArgs.map((registerServiceArg) => {
const args = registerServiceArg.join(", ");
return `export function register${srvName}(${args}): void;`;
}),
].join("\n");
}
}
export class JSTypeGenerator implements TypeGenerator {
bang(field: string): string {
return field;
}
generic(field: string): string {
return field;
}
type(field: string): string {
return field;
}
funcType(): string {
return "";
}
serviceType(): string {
return "";
}
}
export interface AquaFunction {
funcDef: FunctionCallDef;
script: string;
}
export interface CompilationResult {
services: Record<string, ServiceDef>;
functions: Record<string, AquaFunction>;
}
export interface EntityGenerator {
generate(compilationResult: CompilationResult): string;
}
export type OutputType = "js" | "ts";

View File

@ -1,68 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { JSONValue, ServiceDef } from "@fluencelabs/interfaces";
import { recursiveRenameLaquaProps } from "../utils.js";
import { TypeGenerator } from "./interfaces.js";
export function generateServices(
typeGenerator: TypeGenerator,
services: Record<string, ServiceDef>,
) {
const generated = Object.entries(services)
.map(([srvName, srvDef]) => {
return generateService(typeGenerator, srvName, srvDef);
})
.join("\n\n");
return generated + "\n";
}
function generateService(
typeGenerator: TypeGenerator,
srvName: string,
srvDef: ServiceDef,
) {
return [
typeGenerator.serviceType(srvName, srvDef),
generateRegisterServiceOverload(typeGenerator, srvName, srvDef),
].join("\n");
}
function generateRegisterServiceOverload(
typeGenerator: TypeGenerator,
srvName: string,
srvDef: ServiceDef,
) {
return [
`export function register${srvName}(${typeGenerator.type(
"...args",
"any[]",
)}) {`,
" registerService$$(",
" args,",
` ${serviceToJson(srvDef)}`,
" );",
"}",
].join("\n");
}
function serviceToJson(service: ServiceDef): string {
const record: Record<never, JSONValue> = service;
return JSON.stringify(recursiveRenameLaquaProps(record), null, 4);
}

View File

@ -1,65 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { generateSources, generateTypes } from "./generate/index.js";
import { CompilationResult } from "./generate/interfaces.js";
import { getPackageJsonContent } from "./utils.js";
interface JsOutput {
sources: string;
types: string;
}
interface TsOutput {
sources: string;
}
type NothingToGenerate = null;
export default async function aquaToJs(
res: CompilationResult,
outputType: "js",
): Promise<JsOutput | NothingToGenerate>;
export default async function aquaToJs(
res: CompilationResult,
outputType: "ts",
): Promise<TsOutput | NothingToGenerate>;
export default async function aquaToJs(
res: CompilationResult,
outputType: "js" | "ts",
): Promise<JsOutput | TsOutput | NothingToGenerate> {
if (
Object.keys(res.services).length === 0 &&
Object.keys(res.functions).length === 0
) {
return null;
}
const packageJson = await getPackageJsonContent();
if (outputType === "js") {
return {
sources: generateSources(res, "js", packageJson),
types: generateTypes(res, packageJson),
};
}
return {
sources: generateSources(res, "ts", packageJson),
};
}

View File

@ -1,112 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { readFile } from "fs/promises";
import { join } from "path";
import {
ArrowType,
ArrowWithoutCallbacks,
JSONValue,
LabeledProductType,
NilType,
SimpleTypes,
UnlabeledProductType,
} from "@fluencelabs/interfaces";
import { z } from "zod";
const packageJsonSchema = z.object({
name: z.string(),
version: z.string(),
devDependencies: z.object({
// @fluencelabs/aqua-api version is included as part of the comment at the top of each js and ts file
["@fluencelabs/aqua-api"]: z.string(),
}),
});
export type PackageJson = z.infer<typeof packageJsonSchema>;
export async function getPackageJsonContent(): Promise<PackageJson> {
const content = await readFile(
new URL(join("..", "package.json"), import.meta.url),
"utf-8",
);
return packageJsonSchema.parse(JSON.parse(content));
}
export function getFuncArgs(
domain:
| LabeledProductType<SimpleTypes | ArrowType<UnlabeledProductType>>
| UnlabeledProductType
| NilType,
): [string, SimpleTypes | ArrowWithoutCallbacks][] {
if (domain.tag === "labeledProduct") {
return Object.entries(domain.fields).map(([label, type]) => {
return [label, type];
});
} else if (domain.tag === "unlabeledProduct") {
return domain.items.map((type, index) => {
return ["arg" + index, type];
});
} else {
return [];
}
}
export function recursiveRenameLaquaProps(obj: JSONValue): unknown {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => {
return recursiveRenameLaquaProps(item);
});
}
return Object.getOwnPropertyNames(obj).reduce((acc, prop) => {
let accessProp = prop;
if (prop.includes("Laqua_js")) {
// Last part of the property separated by "_" is a correct name
const refinedProperty = prop.split("_").pop();
if (refinedProperty === undefined) {
throw new Error(`Bad property name: ${prop}.`);
}
if (refinedProperty in obj) {
accessProp = refinedProperty;
}
}
const laquaProp = obj[accessProp];
if (laquaProp === undefined) {
return acc;
}
return {
...acc,
[accessProp]: recursiveRenameLaquaProps(laquaProp),
};
}, {});
}
export function capitalize(str: string) {
return str.slice(0, 1).toUpperCase() + str.slice(1);
}

View File

@ -1,9 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"resolveJsonModule": true,
"outDir": "./dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "src/**/__test__"]
}

View File

@ -1,141 +0,0 @@
# Changelog
## [0.12.0](https://github.com/fluencelabs/js-client/compare/interfaces-v0.11.0...interfaces-v0.12.0) (2024-02-23)
### ⚠ BREAKING CHANGES
* **deps:** Update avm to 0.62 ([#438](https://github.com/fluencelabs/js-client/issues/438))
### Bug Fixes
* **deps:** Update avm to 0.62 ([#438](https://github.com/fluencelabs/js-client/issues/438)) ([702ad60](https://github.com/fluencelabs/js-client/commit/702ad605a8e9217f66d3992f31ae8461283ff0b1))
## [0.11.0](https://github.com/fluencelabs/js-client/compare/interfaces-v0.10.0...interfaces-v0.11.0) (2024-01-26)
### ⚠ BREAKING CHANGES
* **deps:** update dependency @fluencelabs/avm to v0.59.0 #423
### Bug Fixes
* **deps:** update dependency @fluencelabs/avm to v0.59.0 [#423](https://github.com/fluencelabs/js-client/issues/423) ([e21ecc1](https://github.com/fluencelabs/js-client/commit/e21ecc1edec5f34f2a56726eb62833774f814fef))
## [0.10.0](https://github.com/fluencelabs/js-client/compare/interfaces-v0.9.0...interfaces-v0.10.0) (2024-01-19)
### ⚠ BREAKING CHANGES
* **deps:** update dependency @fluencelabs/avm to v0.55.0 ([#407](https://github.com/fluencelabs/js-client/issues/407))
### Bug Fixes
* **deps:** update dependency @fluencelabs/avm to v0.55.0 ([5d7ae85](https://github.com/fluencelabs/js-client/commit/5d7ae85e585b8ce1d89f347a0a31d2212fc5a792))
* **deps:** update dependency @fluencelabs/avm to v0.55.0 ([#407](https://github.com/fluencelabs/js-client/issues/407)) ([5d7ae85](https://github.com/fluencelabs/js-client/commit/5d7ae85e585b8ce1d89f347a0a31d2212fc5a792))
## [0.9.0](https://github.com/fluencelabs/js-client/compare/interfaces-v0.8.2...interfaces-v0.9.0) (2023-11-23)
### ⚠ BREAKING CHANGES
* Force release of interfaces ([#388](https://github.com/fluencelabs/js-client/issues/388))
* **js-client:** Segregation of responsibility between js-client packages [fixes DXJ-525] ([#378](https://github.com/fluencelabs/js-client/issues/378))
* Bump avm ([#361](https://github.com/fluencelabs/js-client/issues/361))
* **js-client:** Adding strictes eslint and ts config to all packages [fixes DXJ-464] ([#355](https://github.com/fluencelabs/js-client/issues/355))
### Features
* **aqua-compiler:** JS-client aqua wrapper [fixes DXJ-461] ([#347](https://github.com/fluencelabs/js-client/issues/347)) ([7fff3b1](https://github.com/fluencelabs/js-client/commit/7fff3b1c0374eef76ab4e665b13cf97b5c50ff70))
* Force release of interfaces ([#388](https://github.com/fluencelabs/js-client/issues/388)) ([04c278b](https://github.com/fluencelabs/js-client/commit/04c278b7830aaae5bd83194511de3f942ddd4955))
* **js-client:** Adding strictes eslint and ts config to all packages [fixes DXJ-464] ([#355](https://github.com/fluencelabs/js-client/issues/355)) ([919c7d6](https://github.com/fluencelabs/js-client/commit/919c7d6ea1e9c153ff7a367873c85fb36624125d))
* **js-client:** Segregation of responsibility between js-client packages [fixes DXJ-525] ([#378](https://github.com/fluencelabs/js-client/issues/378)) ([f4a550d](https://github.com/fluencelabs/js-client/commit/f4a550dd226846dfc2ade1ccc35a286dc3be2fed))
* remove obsolete packages [fixes DXJ-462] ([#337](https://github.com/fluencelabs/js-client/issues/337)) ([e7e6176](https://github.com/fluencelabs/js-client/commit/e7e617661f39e1df36a703d5dad93ba52a338919))
### Bug Fixes
* **deps:** Bump avm to 0.54 ([14e91b6](https://github.com/fluencelabs/js-client/commit/14e91b6e00e625792051aee2c82651e5679e3575))
* **deps:** update dependency @fluencelabs/avm to v0.46.0 ([#338](https://github.com/fluencelabs/js-client/issues/338)) ([8e6918c](https://github.com/fluencelabs/js-client/commit/8e6918c4da5bc4cdfe1c840312f477d782d9ca20))
* **deps:** update dependency @fluencelabs/avm to v0.47.0 ([#341](https://github.com/fluencelabs/js-client/issues/341)) ([f186f20](https://github.com/fluencelabs/js-client/commit/f186f209366c29f12e6677e03564ee2fa14b51ae))
* **deps:** update dependency @fluencelabs/avm to v0.48.0 ([#350](https://github.com/fluencelabs/js-client/issues/350)) ([945908a](https://github.com/fluencelabs/js-client/commit/945908a992976f2ad953bcaa3918741f890ffeeb))
* **tests:** Repair integration tests [fixes DXJ-506] ([#364](https://github.com/fluencelabs/js-client/issues/364)) ([36c7619](https://github.com/fluencelabs/js-client/commit/36c7619b4a1e8e2426aaf5592a14e96dafefb273))
### Miscellaneous Chores
* Bump avm ([#361](https://github.com/fluencelabs/js-client/issues/361)) ([29ec812](https://github.com/fluencelabs/js-client/commit/29ec812fc1c5ee812cceb4034776b344e5cadfe5))
## [0.8.2](https://github.com/fluencelabs/js-client/compare/interfaces-v0.8.1...interfaces-v0.8.2) (2023-08-24)
### Features
- use marine-js 0.7.2 ([#321](https://github.com/fluencelabs/js-client/issues/321)) ([c99a509](https://github.com/fluencelabs/js-client/commit/c99a509c8743471856b0beb25696ffe7357d5399))
## [0.8.1](https://github.com/fluencelabs/js-client/compare/interfaces-v0.8.0...interfaces-v0.8.1) (2023-08-08)
### Bug Fixes
- **deps:** update dependency @fluencelabs/avm to v0.43.1 ([#322](https://github.com/fluencelabs/js-client/issues/322)) ([c1d1fa6](https://github.com/fluencelabs/js-client/commit/c1d1fa6659b6dc2c6707786748b3410fab7f1bcd))
## [0.8.0](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.6...interfaces-v0.8.0) (2023-06-29)
### ⚠ BREAKING CHANGES
- **avm:** avm 0.40.0 (https://github.com/fluencelabs/js-client/pull/315)
### Features
- **avm:** avm 0.40.0 (https://github.com/fluencelabs/js-client/pull/315) ([8bae6e2](https://github.com/fluencelabs/js-client/commit/8bae6e24e62153b567f320ccecc7bce76bc826d1))
## [0.7.6](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.5...interfaces-v0.7.6) (2023-06-20)
### Features
- support signatures [fixes DXJ-389] ([#310](https://github.com/fluencelabs/js-client/issues/310)) ([a60dfe0](https://github.com/fluencelabs/js-client/commit/a60dfe0d680b4d9ac5092dec64e2ebf478bf80eb))
## [0.7.5](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.4...interfaces-v0.7.5) (2023-04-04)
### Features
- Cleaning up technical debts ([#295](https://github.com/fluencelabs/js-client/issues/295)) ([0b2f12d](https://github.com/fluencelabs/js-client/commit/0b2f12d8ac223db341d6c30ff403166b3eae2e56))
## [0.7.4](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.3...interfaces-v0.7.4) (2023-03-31)
### Features
- **logs:** Use `debug.js` library for logging [DXJ-327] ([#285](https://github.com/fluencelabs/js-client/issues/285)) ([e95c34a](https://github.com/fluencelabs/js-client/commit/e95c34a79220bd8ecdcee806802ac3d69a2af0cb))
## [0.7.3](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.2...interfaces-v0.7.3) (2023-02-16)
### Bug Fixes
- Trigger release to publish packages that were built ([#262](https://github.com/fluencelabs/js-client/issues/262)) ([47abf38](https://github.com/fluencelabs/js-client/commit/47abf3882956ffbdc52df372db26ba6252e8306b))
## [0.7.2](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.1...interfaces-v0.7.2) (2023-02-16)
### Features
- Add `getRelayPeerId` method for `IFluenceClient` ([#260](https://github.com/fluencelabs/js-client/issues/260)) ([a10278a](https://github.com/fluencelabs/js-client/commit/a10278afaa782a307feb10c4eac060094c101230))
## [0.7.1](https://github.com/fluencelabs/js-client/compare/interfaces-v0.7.0...interfaces-v0.7.1) (2023-02-16)
### Features
- Simplify JS Client public API ([#257](https://github.com/fluencelabs/js-client/issues/257)) ([9daaf41](https://github.com/fluencelabs/js-client/commit/9daaf410964d43228192c829c7ff785db6e88081))
## [0.7.0](https://github.com/fluencelabs/fluence-js/compare/interfaces-v0.6.0...interfaces-v0.7.0) (2023-02-15)
### ⚠ BREAKING CHANGES
- Expose updated JS Client API via `js-client.api` package ([#246](https://github.com/fluencelabs/fluence-js/issues/246))
- Standalone web JS Client ([#243](https://github.com/fluencelabs/fluence-js/issues/243))
### Features
- Expose updated JS Client API via `js-client.api` package ([#246](https://github.com/fluencelabs/fluence-js/issues/246)) ([d4bb8fb](https://github.com/fluencelabs/fluence-js/commit/d4bb8fb42964b3ba25154232980b9ae82c21e627))
- Standalone web JS Client ([#243](https://github.com/fluencelabs/fluence-js/issues/243)) ([9667c4f](https://github.com/fluencelabs/fluence-js/commit/9667c4fec6868f984bba13249f3c47d293396406))
### Bug Fixes
- NodeJS package building ([#248](https://github.com/fluencelabs/fluence-js/issues/248)) ([0d05e51](https://github.com/fluencelabs/fluence-js/commit/0d05e517d89529af513fcb96cfa6c722ccc357a7))

View File

@ -1,54 +0,0 @@
{
"name": "@fluencelabs/interfaces",
"type": "module",
"version": "0.12.0",
"description": "Interfaces",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./fluenceClient": {
"import": "./dist/fluenceClient.js",
"types": "./dist/fluenceClient.d.ts"
},
"./compilerSupport": {
"import": "./dist/compilerSupport.js",
"types": "./dist/compilerSupport.d.ts"
},
"./dist/fluenceClient": {
"import": "./dist/fluenceClient.js",
"types": "./dist/fluenceClient.d.ts"
},
"./dist/compilerSupport": {
"import": "./dist/compilerSupport.js",
"types": "./dist/compilerSupport.d.ts"
}
},
"typesVersions": {
"*": {
"fluenceClient.d.ts": [
"./dist/fluenceClient.d.ts"
],
"compilerSupport.d.ts": [
"./dist/compilerSupport.d.ts"
]
}
},
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {},
"devDependencies": {
"hotscript": "1.0.13"
}
}

View File

@ -1,30 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Peer ID's id as a base58 string (multihash/CIDv0).
*/
export type PeerIdB58 = string;
export type JSONValue =
| string
| number
| boolean
| null
| { [x: string]: JSONValue }
| Array<JSONValue>;
export type JSONObject = { [x: string]: JSONValue };
export type JSONArray = Array<JSONValue>;

View File

@ -1,271 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export type SimpleTypes =
| ScalarType
| OptionType
| ArrayType
| StructType
| TopType
| BottomType
| NilType;
export type NonArrowType = SimpleTypes | ProductType;
export type NonArrowSimpleType =
| SimpleTypes
| UnlabeledProductType
| LabeledProductType<SimpleTypes>;
export type TopType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "topType";
};
export type BottomType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "bottomType";
};
export type OptionType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "option";
/**
* Underlying type of the option
*/
type: SimpleTypes;
};
export type NilType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "nil";
};
export type ArrayType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "array";
/**
* Type of array elements
*/
type: SimpleTypes;
};
/**
* All possible scalar type names
*/
export type ScalarNames =
| "u8"
| "u16"
| "u32"
| "u64"
| "i8"
| "i16"
| "i32"
| "i64"
| "f32"
| "f64"
| "bool"
| "string";
export type ScalarType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "scalar";
/**
* Name of the scalar type
*/
name: ScalarNames;
};
export type StructType = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "struct";
/**
* Struct name
*/
name: string;
/**
* Struct fields
*/
fields: { [key: string]: SimpleTypes };
};
export type LabeledProductType<
T extends
| SimpleTypes
| ArrowType<LabeledProductType<SimpleTypes> | UnlabeledProductType> =
| SimpleTypes
| ArrowType<LabeledProductType<SimpleTypes> | UnlabeledProductType>,
K extends { [key: string]: T } = { [key: string]: T },
> = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "labeledProduct";
/**
* Labelled product fields
*/
fields: K;
};
export type UnlabeledProductType<T extends Array<SimpleTypes> = SimpleTypes[]> =
{
/**
* Type descriptor. Used for pattern-matching
*/
tag: "unlabeledProduct";
/**
* Items in unlabelled product
*/
items: T;
};
export type ProductType = UnlabeledProductType | LabeledProductType;
/**
* ArrowType is a profunctor pointing its domain to codomain.
* Profunctor means variance: Arrow is contravariant on domain, and variant on codomain.
*/
export type ArrowType<
T extends
| LabeledProductType<SimpleTypes | ArrowType<UnlabeledProductType>>
| UnlabeledProductType =
| LabeledProductType<SimpleTypes | ArrowType<UnlabeledProductType>>
| UnlabeledProductType,
> = {
/**
* Type descriptor. Used for pattern-matching
*/
tag: "arrow";
/**
* Where this Arrow is defined
*/
domain: T | NilType;
/**
* Where this Arrow points to
*/
codomain: UnlabeledProductType | NilType;
};
/**
* Arrow which domain contains only non-arrow types
*/
export type ArrowWithoutCallbacks = ArrowType<UnlabeledProductType>;
/**
* Arrow which domain does can contain both non-arrow types and arrows (which themselves cannot contain arrows)
*/
export type ArrowWithCallbacks = ArrowType<
LabeledProductType<SimpleTypes | ArrowWithoutCallbacks>
>;
export interface FunctionCallConstants {
/**
* The name of the relay variable
*/
relay: string;
/**
* The name of the serviceId used load variables at the beginning of the script
*/
getDataSrv: string;
/**
* The name of serviceId is used to execute callbacks for the current particle
*/
callbackSrv: string;
/**
* The name of the serviceId which is called to propagate return value to the generated function caller
*/
responseSrv: string;
/**
* The name of the functionName which is called to propagate return value to the generated function caller
*/
responseFnName: string;
/**
* The name of the serviceId which is called to report errors to the generated function caller
*/
errorHandlingSrv: string;
/**
* The name of the functionName which is called to report errors to the generated function caller
*/
errorFnName: string;
}
/**
* Definition of function (`func` instruction) generated by the Aqua compiler
*/
export interface FunctionCallDef {
/**
* The name of the function in Aqua language
*/
functionName: string;
/**
* Underlying arrow which represents function in aqua
*/
arrow: ArrowWithCallbacks;
/**
* Names of the different entities used in generated air script
*/
names: FunctionCallConstants;
}
/**
* Definition of service registration function (`service` instruction) generated by the Aqua compiler
*/
export interface ServiceDef {
/**
* Default service id. If the service has no default id the value should be undefined
*/
defaultServiceId?: string;
/**
* List of functions which the service consists of
*/
functions:
| LabeledProductType<
ArrowType<LabeledProductType<SimpleTypes> | UnlabeledProductType>
>
| NilType;
}

View File

@ -1,91 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Call, Pipe, Objects, Tuples, Unions, Fn } from "hotscript";
import {
ArrayType,
ArrowType,
LabeledProductType,
NilType,
OptionType,
ScalarType,
SimpleTypes,
StructType,
TopType,
UnlabeledProductType,
} from "./compilerSupport/aquaTypeDefinitions.js";
// Type definitions for inferring ts types from air json definition
// In the future we may remove string type declaration and move to type inference.
type GetTsTypeFromScalar<T extends ScalarType> = [T["name"]] extends [
"u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64" | "f32" | "f64",
]
? number
: [T["name"]] extends ["bool"]
? boolean
: [T["name"]] extends ["string"]
? string
: never;
type MapTuple<T> = {
[K in keyof T]: [T[K]] extends [SimpleTypes] ? GetSimpleType<T[K]> : never;
};
type UnpackIfSingle<T> = [T] extends [[infer R]] ? R : T;
type GetSimpleType<T> = [T] extends [NilType]
? null
: [T] extends [ArrayType]
? GetSimpleType<T["type"]>[]
: [T] extends [StructType]
? { [K in keyof T["fields"]]: GetSimpleType<T["fields"][K]> }
: [T] extends [OptionType]
? GetSimpleType<T["type"]> | null
: [T] extends [ScalarType]
? GetTsTypeFromScalar<T>
: [T] extends [TopType]
? unknown
: never;
interface Access<T> extends Fn {
return: __GetTsType<Call<Objects.Get<this["arg0"]>, T>>;
}
type __GetTsType<T> = [T] extends [SimpleTypes]
? GetSimpleType<T>
: [T] extends [UnlabeledProductType]
? MapTuple<T["items"]>
: [T] extends [LabeledProductType]
? { [K in keyof T["fields"]]: __GetTsType<T["fields"][K]> }
: [T] extends [ArrowType<infer H>]
? (
...t: [H] extends [UnlabeledProductType<infer K>]
? MapTuple<K>
: [H] extends [LabeledProductType<infer _V, infer K>]
? Pipe<K, [Objects.Keys, Unions.ToTuple, Tuples.Map<Access<K>>]>
: []
) => [T["codomain"]] extends [UnlabeledProductType]
? UnpackIfSingle<MapTuple<T["codomain"]["items"]>>
: undefined
: never;
type DeepMutable<T> = {
-readonly [K in keyof T]: DeepMutable<T[K]>;
};
export type GetTsType<T> = __GetTsType<DeepMutable<T>>;

View File

@ -1,9 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

View File

@ -1 +0,0 @@
src/versions.ts

View File

@ -1,113 +0,0 @@
# Changelog
## [0.6.0](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.5.0...js-client-isomorphic-v0.6.0) (2024-02-23)
### ⚠ BREAKING CHANGES
* **deps:** Update avm to 0.62 ([#438](https://github.com/fluencelabs/js-client/issues/438))
### Bug Fixes
* **deps:** Update avm to 0.62 ([#438](https://github.com/fluencelabs/js-client/issues/438)) ([702ad60](https://github.com/fluencelabs/js-client/commit/702ad605a8e9217f66d3992f31ae8461283ff0b1))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* @fluencelabs/marine-worker bumped from 0.5.1 to 0.6.0
## [0.5.0](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.4.0...js-client-isomorphic-v0.5.0) (2024-01-26)
### ⚠ BREAKING CHANGES
* **deps:** update dependency @fluencelabs/avm to v0.59.0 #423
### Bug Fixes
* **deps:** update dependency @fluencelabs/avm to v0.59.0 [#423](https://github.com/fluencelabs/js-client/issues/423) ([e21ecc1](https://github.com/fluencelabs/js-client/commit/e21ecc1edec5f34f2a56726eb62833774f814fef))
## [0.4.0](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.3.1...js-client-isomorphic-v0.4.0) (2024-01-19)
### ⚠ BREAKING CHANGES
* **deps:** update dependency @fluencelabs/avm to v0.55.0 ([#407](https://github.com/fluencelabs/js-client/issues/407))
### Bug Fixes
* **deps:** update dependency @fluencelabs/avm to v0.55.0 ([5d7ae85](https://github.com/fluencelabs/js-client/commit/5d7ae85e585b8ce1d89f347a0a31d2212fc5a792))
* **deps:** update dependency @fluencelabs/avm to v0.55.0 ([#407](https://github.com/fluencelabs/js-client/issues/407)) ([5d7ae85](https://github.com/fluencelabs/js-client/commit/5d7ae85e585b8ce1d89f347a0a31d2212fc5a792))
* Enable async loading of all dependency resources ([#408](https://github.com/fluencelabs/js-client/issues/408)) ([f5425b4](https://github.com/fluencelabs/js-client/commit/f5425b4746f436f84a41bae6584adb8b200ba33d))
## [0.3.1](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.3.0...js-client-isomorphic-v0.3.1) (2023-12-15)
### Features
* **npm-aqua-compiler:** create package ([#401](https://github.com/fluencelabs/js-client/issues/401)) ([d600811](https://github.com/fluencelabs/js-client/commit/d6008110cf0ecaf23a63cfef0bb3f786a6eb0937))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* @fluencelabs/marine-worker bumped from 0.5.0 to 0.5.1
## [0.3.0](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.2.2...js-client-isomorphic-v0.3.0) (2023-11-22)
### ⚠ BREAKING CHANGES
* **js-client:** Segregation of responsibility between js-client packages [fixes DXJ-525] ([#378](https://github.com/fluencelabs/js-client/issues/378))
### Features
* **js-client:** Segregation of responsibility between js-client packages [fixes DXJ-525] ([#378](https://github.com/fluencelabs/js-client/issues/378)) ([f4a550d](https://github.com/fluencelabs/js-client/commit/f4a550dd226846dfc2ade1ccc35a286dc3be2fed))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* @fluencelabs/marine-worker bumped from 0.4.2 to 0.5.0
## [0.2.2](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.2.1...js-client-isomorphic-v0.2.2) (2023-11-06)
### Bug Fixes
* JS-client bugs and tech debt [fixes DXJ-520] ([#374](https://github.com/fluencelabs/js-client/issues/374)) ([b460491](https://github.com/fluencelabs/js-client/commit/b460491fbd0d07e3507a6c70f162014580c6d6da))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* @fluencelabs/marine-worker bumped from 0.4.1 to 0.4.2
## [0.2.1](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.2.0...js-client-isomorphic-v0.2.1) (2023-10-30)
### Bug Fixes
* **deps:** Bump avm to 0.54 ([14e91b6](https://github.com/fluencelabs/js-client/commit/14e91b6e00e625792051aee2c82651e5679e3575))
## [0.2.0](https://github.com/fluencelabs/js-client/compare/js-client-isomorphic-v0.1.0...js-client-isomorphic-v0.2.0) (2023-10-26)
### ⚠ BREAKING CHANGES
* **js-client:** Simplify/optimize js-client and update README [fixes DXJ-490] ([#366](https://github.com/fluencelabs/js-client/issues/366))
### Bug Fixes
* **deps:** Use published threads package ([#369](https://github.com/fluencelabs/js-client/issues/369)) ([a605d75](https://github.com/fluencelabs/js-client/commit/a605d757f9ddf0cb9cb98ef30a88d1c696de3c89))
* Enable publishing of js-client-isomorphic [fixes DXJ-516] ([#370](https://github.com/fluencelabs/js-client/issues/370)) ([bb8fca8](https://github.com/fluencelabs/js-client/commit/bb8fca88e793cb2020cb3fea8f308626c788e6ef))
### Miscellaneous Chores
* **js-client:** Simplify/optimize js-client and update README [fixes DXJ-490] ([#366](https://github.com/fluencelabs/js-client/issues/366)) ([f9abc64](https://github.com/fluencelabs/js-client/commit/f9abc6419c9b32aacec4b05a625d08ec7ff407ba))

View File

@ -1,41 +0,0 @@
/*
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-check
import pkg from "./package.json" assert { type: "json" };
import { writeFile } from "fs/promises";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
const names = [
"@fluencelabs/avm",
"@fluencelabs/marine-js",
"@fluencelabs/marine-worker",
];
const entries = Object.entries({
...pkg.dependencies,
...pkg.devDependencies,
}).filter(([name]) => names.includes(name));
const output = Object.fromEntries(entries);
await writeFile(
join(dirname(fileURLToPath(import.meta.url)), "src", "versions.ts"),
`/* eslint-disable */
export default ${JSON.stringify(output, null, 2)} as const`,
);

View File

@ -1,33 +0,0 @@
{
"type": "module",
"name": "@fluencelabs/js-client-isomorphic",
"version": "0.6.0",
"description": "Isomorphic entities for js-client",
"files": [
"dist"
],
"scripts": {
"build": "tsc",
"prepare": "node createVersionFile.js"
},
"exports": {
".": "./dist/types.js",
"./fetcher": {
"node": "./dist/fetchers/node.js",
"default": "./dist/fetchers/browser.js"
},
"./worker-resolver": {
"node": "./dist/worker-resolvers/node.js",
"default": "./dist/worker-resolvers/browser.js"
}
},
"dependencies": {
"@fluencelabs/avm": "0.62.0",
"@fluencelabs/marine-js": "0.13.0",
"@fluencelabs/marine-worker": "0.6.0",
"@fluencelabs/threads": "^2.0.0"
},
"keywords": [],
"author": "Fluence Labs",
"license": "Apache-2.0"
}

View File

@ -1,35 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FetchResourceFn, getVersionedPackage } from "../types.js";
/**
* @param pkg name of package with version
* @param assetPath path of required asset in given package
* @param root CDN domain in browser or file system root in node
*/
export const fetchResource: FetchResourceFn = async (pkg, assetPath, root) => {
const refinedAssetPath = assetPath.startsWith("/")
? assetPath.slice(1)
: assetPath;
const { name, version } = getVersionedPackage(pkg);
const url = new URL(`${name}@${version}/` + refinedAssetPath, root);
return fetch(url).catch(() => {
throw new Error(`Cannot fetch from ${url.toString()}`);
});
};

View File

@ -1,56 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { readFile } from "fs/promises";
import { createRequire } from "module";
import { sep, posix, join } from "path";
import { FetchResourceFn, getVersionedPackage } from "../types.js";
/**
* @param pkg name of package with version
* @param assetPath path of required asset in given package
*/
export const fetchResource: FetchResourceFn = async (pkg, assetPath) => {
const { name } = getVersionedPackage(pkg);
const require = createRequire(import.meta.url);
const packagePathIndex = require.resolve(name);
// Ensure that windows path is converted to posix path. So we can find a package
const posixPath = packagePathIndex.split(sep).join(posix.sep);
const matches = new RegExp(`(.+${name})`).exec(posixPath);
const packagePath = matches?.[0];
if (packagePath === undefined) {
throw new Error(`Cannot find dependency ${name} in path ${posixPath}`);
}
const pathToResource = join(packagePath, assetPath);
const file = await readFile(pathToResource);
return new Response(file, {
headers: {
"Content-type": assetPath.endsWith(".wasm")
? "application/wasm"
: assetPath.endsWith(".js")
? "application/javascript"
: "application/text",
},
});
};

View File

@ -1,40 +0,0 @@
/**
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { MarineBackgroundInterface } from "@fluencelabs/marine-worker";
import { ModuleThread } from "@fluencelabs/threads/master";
import versions from "./versions.js";
export type FetchedPackages = keyof typeof versions;
type VersionedPackage = { name: string; version: string };
export type GetWorkerFn = (
pkg: FetchedPackages,
CDNUrl: string,
) => Promise<ModuleThread<MarineBackgroundInterface>>;
export const getVersionedPackage = (pkg: FetchedPackages): VersionedPackage => {
return {
name: pkg,
version: versions[pkg],
};
};
export type FetchResourceFn = (
pkg: FetchedPackages,
assetPath: string,
root: string,
) => Promise<Response>;

Some files were not shown because too many files have changed in this diff Show More