Skip to content

Commit

Permalink
chore: sync with w3up repo (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
fforbeck authored Jan 16, 2025
1 parent 1390106 commit d86e52c
Show file tree
Hide file tree
Showing 9 changed files with 320 additions and 13 deletions.
3 changes: 2 additions & 1 deletion .attw.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"ignoreRules": ["cjs-resolves-to-esm"]
"ignoreRules": ["cjs-resolves-to-esm"],
"excludeEntrypoints": ["browser.min.js"]
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ docs
.env
.next
out
*.min.js

# debug
npm-debug.log*
Expand Down
3 changes: 2 additions & 1 deletion packages/upload-client/src/blob/add.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import retry, { AbortError } from 'p-retry'
import { servicePrincipal, connection } from '../service.js'
import { REQUEST_RETRIES } from '../constants.js'
import { poll } from '../receipts.js'
import { isCloudflareWorkers } from '../runtime.js'

/**
* @param {string} url
Expand Down Expand Up @@ -227,7 +228,7 @@ export async function add(
try {
const res = await fetchWithUploadProgress(address.url, {
method: 'PUT',
mode: 'cors',
...(!isCloudflareWorkers && { mode: 'cors' }),
body: bytes,
headers: address.headers,
signal: options.signal,
Expand Down
27 changes: 22 additions & 5 deletions packages/upload-client/src/receipts.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import retry, { AbortError } from 'p-retry'
import { CAR } from '@ucanto/transport'
import { receiptsEndpoint } from './service.js'
import { receiptsEndpoint as defaultReceiptsEndpoint } from './service.js'
import { REQUEST_RETRIES } from './constants.js'

export class ReceiptNotFound extends Error {
Expand Down Expand Up @@ -77,6 +77,20 @@ export async function poll(taskCid, options = {}) {
)
}

/**
* Calculate a receipt endpoint from the URL of a channel, if it has one.
*
* @param {import('@ucanto/interface').Channel<Record<string, any>>} channel
*/
function receiptEndpointFromChannel(channel) {
if ('url' in channel && channel.url instanceof URL) {
const url = channel.url
return new URL('/receipt/', url.toString())
} else {
return null
}
}

/**
* Get a receipt for an executed task by its CID.
*
Expand All @@ -85,11 +99,14 @@ export async function poll(taskCid, options = {}) {
* @returns {Promise<import('@ucanto/client').Result<import('@ucanto/interface').Receipt, Error>>}
*/
async function get(taskCid, options = {}) {
const channel = options.connection?.channel
const receiptsEndpoint =
options.receiptsEndpoint ??
(channel && receiptEndpointFromChannel(channel)) ??
defaultReceiptsEndpoint

// Fetch receipt from endpoint
const url = new URL(
taskCid.toString(),
options.receiptsEndpoint ?? receiptsEndpoint
)
const url = new URL(taskCid.toString(), receiptsEndpoint)
const fetchReceipt = options.fetch ?? globalThis.fetch.bind(globalThis)
const workflowResponse = await fetchReceipt(url)
/* c8 ignore start */
Expand Down
4 changes: 4 additions & 0 deletions packages/upload-client/src/runtime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* c8 ignore next 3 */
export const isCloudflareWorkers =
typeof navigator !== 'undefined' &&
navigator?.userAgent === 'Cloudflare-Workers'
16 changes: 15 additions & 1 deletion packages/w3up-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

This library is the user-facing "porcelain" client for interacting with w3up services from JavaScript. It wraps the lower-level [`@storacha/access`][access-client-github] and [`@storacha/upload-client`][upload-client-github] client packages, which target individual w3up services. We recommend using `@storacha/client` instead of using those "plumbing" packages directly, but you may find them useful if you need more context on w3up's architecture and internals.

**`w3up-client` requires Node 18 or higher**.
**`w3up-client` requires modern browser or Node 18+**.

> ⚠️❗ __Public Data__ 🌎: All data uploaded to w3up is available to anyone who requests it using the correct CID. Do not store any private or sensitive information in an unencrypted form using w3up.
Expand Down Expand Up @@ -117,6 +117,20 @@ const client = await create({ principal })

Once initialized, you can access the client's `Agent` with the [`agent` getter][docs-Client#agent].

##### Pre-built bundle
You can also import a pre-built bundle, which adds the exports from the client to a _global_ variable `StorachaClient`:
```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@storacha/client/browser.min.js"></script>
<script>
async function main () {
const client = await StorachaClient.create()
console.log(client.did())
}
main()
</script>
```

#### Creating and registering Spaces

A [`Space`][docs-Space] acts as a namespace for your uploads, and what your Agent will need a delegation from to store data with w3up. The first thing to do is login your Agent with your email address. Calling `login` will cause an email to be sent to the given address. Once a user clicks the confirmation link in the email, the `login` method will resolve. Make sure to check for errors, as `login` will fail if the email is not confirmed within the expiration timeout. Authorization needs to happen only once per agent.
Expand Down
14 changes: 11 additions & 3 deletions packages/w3up-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
"types": "./dist/src/account.d.ts",
"import": "./dist/src/account.js"
},
"./browser.min.js": {
"default": "./browser.min.js"
},
"./delegation": {
"types": "./dist/src/delegation.d.ts",
"import": "./dist/src/delegation.js"
Expand Down Expand Up @@ -114,13 +117,16 @@
"access": "public"
},
"files": [
"dist"
"dist",
"*.min.js"
],
"scripts": {
"attw": "attw --pack .",
"lint": "tsc --build && eslint '**/*.{js,ts}' && prettier --check '**/*.{js,ts,yml,json}' --ignore-path ../../.gitignore",
"lint:fix": "tsc --build && eslint '**/*.{js,ts}' --fix && prettier --write '**/*.{js,ts,yml,json}' --ignore-path ../../.gitignore",
"build": "tsc --build",
"build": "npm run build:tsc && npm run build:bundle:browser",
"build:tsc": "tsc --build",
"build:bundle:browser": "esbuild src/index.js --bundle --minify --target=chrome130 --format=iife --global-name=StorachaClient --outfile=browser.min.js",
"dev": "tsc --build --watch",
"check": "tsc --build",
"prepare": "npm run build",
Expand Down Expand Up @@ -166,6 +172,7 @@
"@web3-storage/w3up-client": "^16.5.1",
"assert": "^2.0.0",
"c8": "^7.13.0",
"esbuild": "^0.24.0",
"hundreds": "^0.0.9",
"mocha": "^10.8.2",
"multiformats": "^12.1.2",
Expand All @@ -192,7 +199,8 @@
"docs",
"docs-generated",
"coverage",
"src/types.js"
"src/types.js",
"*.min.js"
]
},
"directories": {
Expand Down
4 changes: 2 additions & 2 deletions packages/w3up-client/src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ export class Client extends Base {
* It is done by delegating the `space/content/serve/*` capability to the Gateway Service.
* User can skip the Gateway authorization by setting the `skipGatewayAuthorization` option to `true`.
* If no gateways are specified or the `skipGatewayAuthorization` flag is not set, the client will automatically grant access
* to the Storacha Gateway by default (https://freewaying.dag.haus/).
* to the Storacha Gateway by default (https://w3s.link/).
*
* @typedef {import('./types.js').ConnectionView<import('./types.js').ContentServeService>} ConnectionView
*
Expand Down Expand Up @@ -322,7 +322,7 @@ export class Client extends Base {
channel: HTTP.open({
url: new URL(
/* c8 ignore next - default prod gateway url is not used in tests */
process.env.DEFAULT_GATEWAY_URL ?? 'https://freeway.dag.haus'
process.env.DEFAULT_GATEWAY_URL ?? 'https://w3s.link'
),
}),
}),
Expand Down
Loading

0 comments on commit d86e52c

Please sign in to comment.