### Run Examples for JS Package Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Execute example scripts for the JavaScript package by navigating to the 'pkg' directory and running the example command. ```bash cd pkg npm run example ``` -------------------------------- ### Install and Test JS Package Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md After building, navigate to the 'pkg' directory to install and run tests for the JavaScript package. ```bash cd pkg npm run install npm run test ``` -------------------------------- ### Creating a Post Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Shows how to create a new post object using `PubkySpecsBuilder.createPost`. This example covers basic post content and type, and how to store it. ```APIDOC ## 2) Creating a Post ```js import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder, PubkyAppPostKind } from "pubky-app-specs"; async function createPost(pubkyId, content) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // Create the Post object const { post, meta } = specs.createPost( content, PubkyAppPostKind.Short, null, // parent post URI (for replies) null, // embed object (for reposts) null, // attachments (array of file URLs, max 3) ); // Store the post const postJson = post.toJson(); await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(postJson), }); console.log("Post stored at:", meta.url); return { post, meta }; } ``` ``` -------------------------------- ### Valid PubkyAppPost Example Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Demonstrates the structure of a valid user post, including content, kind, parent, embed, and attachments. ```json { "content": "Hello world! This is my first post.", "kind": "short", "parent": null, "embed": { "kind": "short", "uri": "pubky://user_id/pub/pubky.app/posts/0000000000000" }, "attachments": ["pubky://user_id/pub/pubky.app/files/0000000000000"] } ``` -------------------------------- ### Install pubky-app-specs with npm Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Use this command to install the library using npm. The package includes WASM with embedded bytes for automatic initialization. ```bash npm install pubky-app-specs ``` -------------------------------- ### Install pubky-app-specs with yarn Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Use this command to install the library using yarn. The package includes WASM with embedded bytes for automatic initialization. ```bash yarn add pubky-app-specs ``` -------------------------------- ### Following a User Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Explains how to use `PubkySpecsBuilder.createFollow` to establish a follow relationship with another user. The example shows storing the follow action on the homeserver. ```APIDOC ## 4) Following a User ```js import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder } from "pubky-app-specs"; async function followUser(myPubkyId, userToFollow) { const client = new Client(); const specs = new PubkySpecsBuilder(myPubkyId); const { follow, meta } = specs.createFollow(userToFollow); // We only need to store the JSON in the homeserver await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(follow.toJson()), }); console.log(`Successfully followed: ${userToFollow}`); } ``` ``` -------------------------------- ### Create a Post with Attachments using PubkySpecsBuilder Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Example of creating a post that includes attachments. The `createPost` method accepts an array of file URLs, with a maximum of three attachments allowed. The post is then stored. ```javascript import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder, PubkyAppPostKind } from "pubky-app-specs"; async function createPostWithAttachments(pubkyId, content, fileUrls) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // Create post with attachments (max 3 allowed) const { post, meta } = specs.createPost( content, PubkyAppPostKind.Image, null, // parent null, // embed fileUrls, // e.g. ["pubky://user/pub/pubky.app/files/abc123"] ); const postJson = post.toJson(); console.log("Attachments:", postJson.attachments); await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(postJson), }); console.log("Post with attachments stored at:", meta.url); return { post, meta }; } ``` -------------------------------- ### Create a New User with PubkySpecsBuilder Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Example of creating a new user object using PubkySpecsBuilder. The `createUser` method returns the user object and metadata. The user object needs to be converted to JSON before storing. ```javascript import { Client, PublicKey } from "@synonymdev/pubky"; import { PubkySpecsBuilder } from "pubky-app-specs"; async function createUser(pubkyId) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // Create user object with minimal fields const { user, meta } = specs.createUser( "Alice", // Name "Hello from WASM", // Bio null, // Image URL or File null, // Links "active", // Status ); // meta contains { id, path, url }. // user is the Rust "PubkyAppUser" object. // We bring the Rust object to JS using the .toJson() method. const userJson = user.toJson(); // Store in homeserver via pubky const response = await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(userJson), credentials: "include", }); if (!response.ok) { throw new Error(`Failed to store user: ${response.statusText}`); } console.log("User stored at:", meta.url); return { user, meta }; } ``` -------------------------------- ### JavaScript Client Deserialization Example Source: https://github.com/pubky/pubky-app-specs/blob/main/docs/UNICODE_NOTES.md Example of how a JavaScript client might deserialize JSON data, including Unicode characters, before sending it to the WASM module for validation. ```javascript const user = PubkyAppUser.fromJson({ name: "Alice🔥", bio: "Hello 𓀀" }); ``` -------------------------------- ### Valid PubkyAppUser JSON Example Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md This is an example of a valid PubkyAppUser JSON object. It includes fields for name, bio, image, links, and status, adhering to specified validation rules. ```json { "name": "Alice", "bio": "Toxic maximalist.", "image": "pubky://user_id/pub/pubky.app/files/0000000000000", "links": [ { "title": "GitHub", "url": "https://github.com/alice" } ], "status": "Exploring decentralized tech." } ``` -------------------------------- ### Get and Validate File MIME Types Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Retrieve a list of allowed MIME types for file attachments using `getValidMimeTypes()`. This list can be used to validate file types before upload, preventing the upload of unsupported file formats. ```javascript import { getValidMimeTypes } from "pubky-app-specs"; // Get the list of valid MIME types const validMimeTypes = getValidMimeTypes(); // Returns: ["application/javascript", "application/json", "application/pdf", "image/png", ...] // Validate a file before upload function isValidFileType(mimeType) { return validMimeTypes.includes(mimeType); } // Example usage if (isValidFileType(file.type)) { // Proceed with upload } else { console.error(`Invalid file type: ${file.type}`); } ``` -------------------------------- ### Creating a New User Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Illustrates the process of creating a new user object using `PubkySpecsBuilder.createUser`. It covers minimal fields and shows how to store the created user data on a PubKy homeserver. ```APIDOC ## 1) Creating a New User ```js import { Client, PublicKey } from "@synonymdev/pubky"; import { PubkySpecsBuilder } from "pubky-app-specs"; async function createUser(pubkyId) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // Create user object with minimal fields const { user, meta } = specs.createUser( "Alice", // Name "Hello from WASM", // Bio null, // Image URL or File null, // Links "active", // Status ); // meta contains { id, path, url }. // user is the Rust "PubkyAppUser" object. // We bring the Rust object to JS using the .toJson() method. const userJson = user.toJson(); // Store in homeserver via pubky const response = await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(userJson), credentials: "include", }); if (!response.ok) { throw new Error(`Failed to store user: ${response.statusText}`); } console.log("User stored at:", meta.url); return { user, meta }; } ``` ``` -------------------------------- ### Build JS Package from Source Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Navigate to the 'pkg' directory and run the build script to compile the JavaScript package. ```bash cd pkg npm run build ``` -------------------------------- ### Importing and Initializing PubkySpecsBuilder Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Demonstrates how to import the PubkySpecsBuilder from the library and initialize it with a Pubky ID. This is the first step before creating any data objects. ```APIDOC ## Import & Usage ```js // ES Modules import { PubkySpecsBuilder } from "pubky-app-specs"; // OR CommonJS const { PubkySpecsBuilder } = require("pubky-app-specs"); function loadSpecs(pubkyId) { // Create a specs builder instance - WASM is already initialized const specs = new PubkySpecsBuilder(pubkyId); return specs; } ``` ``` -------------------------------- ### Create a Post with PubkySpecsBuilder Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Demonstrates creating a new post using PubkySpecsBuilder. The `createPost` method takes content and post kind as arguments. The resulting post object is then stored. ```javascript import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder, PubkyAppPostKind } from "pubky-app-specs"; async function createPost(pubkyId, content) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // Create the Post object const { post, meta } = specs.createPost( content, PubkyAppPostKind.Short, null, // parent post URI (for replies) null, // embed object (for reposts) null, // attachments (array of file URLs, max 3) ); // Store the post const postJson = post.toJson(); await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(postJson), }); console.log("Post stored at:", meta.url); return { post, meta }; } ``` -------------------------------- ### Pubky App Specs Demo Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/index.html This snippet demonstrates creating a user, a post, and a follow relationship using the PubkySpecsBuilder. It includes basic error handling. Ensure the PubkySpecsBuilder, PubkyAppPostKind, and PubkyAppPostEmbed are imported from './index.js'. ```javascript import { PubkySpecsBuilder, PubkyAppPostKind, PubkyAppPostEmbed } from "./index.js"; async function main() { try { // Test various functions like the example.js const OTTO = "8kkppkmiubfq4pxn6f73nqrhhhgkb5xyfprntc9si3np9ydbotto"; const RIO = "dzswkfy7ek3bqnoc89jxuqqfbzhjrj6mi8qthgbxxcqkdugm3rio"; const specsBuilder = new PubkySpecsBuilder(OTTO); // Create a user const { user, meta: userMeta } = specsBuilder.createUser("Alice Smith", "Software Developer", null, null, "active"); console.log("User created:", userMeta.url); // Create a post const { post, meta: postMeta } = specsBuilder.createPost("Hello from browser!", PubkyAppPostKind.Short, null, null, null); console.log("Post created:", postMeta.url); // Create a follow const { follow, meta: followMeta } = specsBuilder.createFollow(RIO); console.log("Follow created:", followMeta.url); console.log("All tests passed!"); } catch (err) { console.error("Error:", err); } } main(); ``` -------------------------------- ### Import PubkySpecsBuilder Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Demonstrates how to import the PubkySpecsBuilder class for both ES Modules and CommonJS environments. Initialize the builder with a pubkyId. ```javascript // ES Modules import { PubkySpecsBuilder } from "pubky-app-specs"; // OR CommonJS const { PubkySpecsBuilder } = require("pubky-app-specs"); function loadSpecs(pubkyId) { // Create a specs builder instance - WASM is already initialized const specs = new PubkySpecsBuilder(pubkyId); return specs; } ``` -------------------------------- ### Creating a Post with Attachments Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Demonstrates creating a post that includes attachments. This function highlights the `attachments` parameter in `PubkySpecsBuilder.createPost`, which accepts an array of file URLs (up to 3). ```APIDOC ## 3) Creating a Post with Attachments ```js import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder, PubkyAppPostKind } from "pubky-app-specs"; async function createPostWithAttachments(pubkyId, content, fileUrls) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // Create post with attachments (max 3 allowed) const { post, meta } = specs.createPost( content, PubkyAppPostKind.Image, null, // parent null, // embed fileUrls, // e.g. ["pubky://user/pub/pubky.app/files/abc123"] ); const postJson = post.toJson(); console.log("Attachments:", postJson.attachments); await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(postJson), }); console.log("Post with attachments stored at:", meta.url); return { post, meta }; } ``` ``` -------------------------------- ### Follow a User with PubkySpecsBuilder Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Shows how to create a follow relationship using PubkySpecsBuilder. The `createFollow` method generates the necessary data structure, which is then stored on the homeserver. ```javascript import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder } from "pubky-app-specs"; async function followUser(myPubkyId, userToFollow) { const client = new Client(); const specs = new PubkySpecsBuilder(myPubkyId); const { follow, meta } = specs.createFollow(userToFollow); // We only need to store the JSON in the homeserver await client.fetch(meta.url, { method: "PUT", body: JSON.stringify(follow.toJson()), }); console.log(`Successfully followed: ${userToFollow}`); } ``` -------------------------------- ### Create File with Blob using Pubky Client Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Use this function to upload a file by first creating and storing its raw binary data as a blob, then creating file metadata that references the blob. Ensure the client is initialized and specs are built for the target pubkyId. ```javascript import { Client } from "@synonymdev/pubky"; import { PubkySpecsBuilder, getValidMimeTypes } from "pubky-app-specs"; async function uploadFile(pubkyId, fileData, fileName, contentType, fileSize) { const client = new Client(); const specs = new PubkySpecsBuilder(pubkyId); // First, create and store the blob (raw binary data) const { blob, meta: blobMeta } = specs.createBlob(fileData); await client.fetch(blobMeta.url, { method: "PUT", body: JSON.stringify(blob.toJson()), }); // Then create the file metadata pointing to the blob const { file, meta: fileMeta } = specs.createFile( fileName, // e.g. "vacation-photo.jpg" blobMeta.url, // Reference to the blob contentType, // e.g. "image/jpeg" fileSize, // Size in bytes ); await client.fetch(fileMeta.url, { method: "PUT", body: JSON.stringify(file.toJson()), }); console.log("File stored at:", fileMeta.url); return { file, meta: fileMeta }; } ``` -------------------------------- ### Build Pubky URIs Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Use these builders to construct valid Pubky URIs for various resources. Ensure the 'pubky-app-specs' library is imported. ```javascript import { userUriBuilder, postUriBuilder, bookmarkUriBuilder, followUriBuilder, tagUriBuilder, muteUriBuilder, lastReadUriBuilder, blobUriBuilder, fileUriBuilder, feedUriBuilder, } from "pubky-app-specs"; const userId = "8kkppkmiubfq4pxn6f73nqrhhhgkb5xyfprntc9si3np9ydbotto"; const targetUserId = "dzswkfy7ek3bqnoc89jxuqqfbzhjrj6mi8qthgbxxcqkdugm3rio"; // Build URIs for different resources userUriBuilder(userId); // pubky://{userId}/pub/pubky.app/profile.json postUriBuilder(userId, "0033SSE3B1FQ0"); // pubky://{userId}/pub/pubky.app/posts/{postId} bookmarkUriBuilder(userId, "ABC123"); // pubky://{userId}/pub/pubky.app/bookmarks/{bookmarkId} followUriBuilder(userId, targetUserId); // pubky://{userId}/pub/pubky.app/follows/{targetUserId} tagUriBuilder(userId, "XYZ789"); // pubky://{userId}/pub/pubky.app/tags/{tagId} contentInsetUriBuilder(userId, targetUserId); // pubky://{userId}/pub/pubky.app/mutes/{targetUserId} lastReadUriBuilder(userId); // pubky://{userId}/pub/pubky.app/last_read blobUriBuilder(userId, "BLOB123"); // pubky://{userId}/pub/pubky.app/blobs/{blobId} fileUriBuilder(userId, "FILE456"); // pubky://{userId}/pub/pubky.app/files/{fileId} feedUriBuilder(userId, "FEED789"); // pubky://{userId}/pub/pubky.app/feeds/{feedId} ``` -------------------------------- ### URI Builder Utilities Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Helper functions to construct properly formatted Pubky URIs for various resources. ```APIDOC ## URI Builder Utilities These helper functions construct properly formatted Pubky URIs: ### `userUriBuilder(userId)` Builds a URI for a user profile. ### `postUriBuilder(userId, postId)` Builds a URI for a specific post. ### `bookmarkUriBuilder(userId, bookmarkId)` Builds a URI for a bookmark. ### `followUriBuilder(userId, targetUserId)` Builds a URI for a follow relationship. ### `tagUriBuilder(userId, tagId)` Builds a URI for a tag. ### `muteUriBuilder(userId, targetUserId)` Builds a URI for a mute relationship. ### `lastReadUriBuilder(userId)` Builds a URI for the last read status. ### `blobUriBuilder(userId, blobId)` Builds a URI for a blob. ### `fileUriBuilder(userId, fileId)` Builds a URI for a file. ### `feedUriBuilder(userId, feedId)` Builds a URI for a feed. ``` -------------------------------- ### PubkyAppFile Metadata Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents metadata for a file uploaded by a user. Includes file name, creation timestamp, source URL, content type, and size. ```APIDOC ## GET /pub/pubky.app/files/:file_id ### Description Retrieves metadata for a specific file. ### Method GET ### Endpoint /pub/pubky.app/files/:file_id ### Parameters #### Path Parameters - **file_id** (string) - Required - The unique Timestamp ID of the file. ### Response #### Success Response (200) - **name** (string) - Name of the file. - **created_at** (integer) - Unix timestamp of creation. - **src** (string) - File blob URL. - **content_type** (string) - MIME type of the file. - **size** (integer) - Size of the file in bytes. ### Response Example ```json { "name": "document.pdf", "created_at": 1678886400, "src": "pubky://user_id/pub/pubky.app/files/0000000000001", "content_type": "application/pdf", "size": 512000 } ``` ``` ```APIDOC ## POST /pub/pubky.app/files ### Description Uploads a new file and returns its metadata. ### Method POST ### Endpoint /pub/pubky.app/files ### Parameters #### Request Body - **name** (string) - Required - Name of the file. - **created_at** (integer) - Required - Unix timestamp of creation. - **src** (string) - Required - File blob URL. - **content_type** (string) - Required - MIME type of the file. - **size** (integer) - Required - Size of the file in bytes. ### Request Example ```json { "name": "image.jpg", "created_at": 1678886400, "src": "pubky://user_id/pub/pubky.app/files/0000000000002", "content_type": "image/jpeg", "size": 102400 } ``` ### Response #### Success Response (200) - **name** (string) - Name of the file. - **created_at** (integer) - Unix timestamp of creation. - **src** (string) - File blob URL. - **content_type** (string) - MIME type of the file. - **size** (integer) - Size of the file in bytes. ### Response Example ```json { "name": "image.jpg", "created_at": 1678886400, "src": "pubky://user_id/pub/pubky.app/files/0000000000002", "content_type": "image/jpeg", "size": 102400 } ``` ``` -------------------------------- ### PubkyAppFeed Configuration Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents a feed configuration with various properties for filtering and display. ```APIDOC ## GET /pub/pubky.app/feeds/:feed_id ### Description Retrieves the configuration for a specific PubkyAppFeed. ### Method GET ### Endpoint /pub/pubky.app/feeds/:feed_id ### Parameters #### Path Parameters - **feed_id** (string) - Required - The unique identifier for the feed. ### Response #### Success Response (200) - **tags** (Array) - Optional - List of tags for filtering. Strings must be trimmed. - **reach** (String) - Required - Feed visibility (e.g., `all`, `friends`). Must be a valid reach. - **layout** (String) - Required - Feed layout style (e.g., `columns`). Must be valid layout. - **sort** (String) - Required - Sort order (e.g., `recent`). Must be valid sort. - **content** (String) - Optional - Type of content filtered. - **name** (String) - Required - Name of the feed. ``` ```APIDOC ## PUT /pub/pubky.app/feeds/:feed_id ### Description Updates the configuration for a specific PubkyAppFeed. ### Method PUT ### Endpoint /pub/pubky.app/feeds/:feed_id ### Parameters #### Path Parameters - **feed_id** (string) - Required - The unique identifier for the feed. #### Request Body - **tags** (Array) - Optional - List of tags for filtering. Strings must be trimmed. - **reach** (String) - Required - Feed visibility (e.g., `all`, `friends`). Must be a valid reach. - **layout** (String) - Required - Feed layout style (e.g., `columns`). Must be valid layout. - **sort** (String) - Required - Sort order (e.g., `recent`). Must be valid sort. - **content** (String) - Optional - Type of content filtered. - **name** (String) - Required - Name of the feed. ### Response #### Success Response (200) - **tags** (Array) - Optional - List of tags for filtering. Strings must be trimmed. - **reach** (String) - Required - Feed visibility (e.g., `all`, `friends`). Must be a valid reach. - **layout** (String) - Required - Feed layout style (e.g., `columns`). Must be valid layout. - **sort** (String) - Required - Sort order (e.g., `recent`). Must be valid sort. - **content** (String) - Optional - Type of content filtered. - **name** (String) - Required - Name of the feed. ``` -------------------------------- ### PubkyAppBookmark Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents a bookmark to a specific URI within the Pubky application. ```APIDOC ## POST /pub/pubky.app/bookmarks/:bookmark_id ### Description Creates a bookmark for a given URI. ### Method POST ### Endpoint `/pub/pubky.app/bookmarks/:bookmark_id` ### Parameters #### Path Parameters - **bookmark_id** (string) - Required - The Hash ID derived from the URI. #### Request Body - **uri** (string) - Required - The URI to bookmark. Must be a valid URI. - **created_at** (integer) - Required - Timestamp of creation. ``` -------------------------------- ### Validate User Creation with Pubky WASM Module Source: https://github.com/pubky/pubky-app-specs/blob/main/docs/UNICODE_NOTES.md Use the PubkySpecsBuilder or PubkyAppUser.fromJson to automatically validate user objects. Exceptions are thrown on validation failure, eliminating the need for manual checks. ```javascript import { PubkySpecsBuilder, PubkyAppUser } from "pubky-app-specs"; // Method 1: Using builder try { const builder = new PubkySpecsBuilder(userId); const { user } = builder.createUser( "Alice🔥", // Emoji counts as 1 character "Bio with 𓀀", // Hieroglyph counts as 1 character null, null, null ); console.log("User is valid!"); } catch (error) { showError(error.message); // Validation failed } // Method 2: From JSON try { const user = PubkyAppUser.fromJson({ name: "Alice🔥", bio: "Bio with 𓀀", image: null, links: null, status: null }); console.log("User is valid!"); } catch (error) { showError(error.message); // Validation failed } // Both methods throw on validation failure - no manual checks needed! ``` -------------------------------- ### PubkyAppPost Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents a user's post within the Pubky application. Supports various content types and attachments. ```APIDOC ## POST /pub/pubky.app/posts/:post_id ### Description Creates or updates a user's post. ### Method POST ### Endpoint `/pub/pubky.app/posts/:post_id` ### Parameters #### Path Parameters - **post_id** (string) - Required - The unique identifier for the post. #### Request Body - **content** (string) - Required - The main content of the post. Max length: 2000 (short) or 50000 (long). Cannot be `"[DELETED]"`. - **kind** (string) - Required - The type of post. Must be a valid `PubkyAppPostKind` value (e.g., `short`, `long`, `image`, `video`, `link`, `file`, `collection`). - **parent** (string) - Optional - The URI of the parent post if this is a reply. Must be a valid URI if present. - **embed** (object) - Optional - Reposted content, containing `kind` (string) and `uri` (string). URI must be valid if present. - **attachments** (array) - Optional - A list of URIs for attached files. Each must be a valid URI. ### Request Example ```json { "content": "Hello world! This is my first post.", "kind": "short", "parent": null, "embed": { "kind": "short", "uri": "pubky://user_id/pub/pubky.app/posts/0000000000000" }, "attachments": ["pubky://user_id/pub/pubky.app/files/0000000000000"] } ``` ### Note on `kind = collection` For `kind = collection`, the `content` field uses a typed JSON envelope with fields like `name`, `description`, `cover_image`, and `items`. `parent`, `embed`, and `post.attachments` must be unset. The `content` field has a bounded length of 40000 scalars. ``` -------------------------------- ### PubkyAppTag Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents a tag applied to a specific URI within the Pubky application. ```APIDOC ## POST /pub/pubky.app/tags/:tag_id ### Description Creates a tag for a given URI. ### Method POST ### Endpoint `/pub/pubky.app/tags/:tag_id` ### Parameters #### Path Parameters - **tag_id** (string) - Required - The Hash ID derived from the URI and label. #### Request Body - **uri** (string) - Required - The URI of the object to be tagged. Must be a valid URI. - **label** (string) - Required - The label for the tag. Trimmed, lowercase, max length: 20 characters. - **created_at** (integer) - Required - Unix timestamp of creation. ``` -------------------------------- ### Import Validation Limits (ESM/CJS) Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Import validation limits using named exports from the package root or direct subpath imports for ESM and CJS environments. ```javascript import { validationLimits, getValidationLimits } from "pubky-app-specs"; console.log(validationLimits); const copy = getValidationLimits(); ``` ```javascript import limits from "pubky-app-specs/validationLimits"; // or import limitsJson from "pubky-app-specs/validationLimits.json"; ``` ```javascript const { validationLimits, getValidationLimits } = require("pubky-app-specs"); // or const limits = require("pubky-app-specs/validationLimits"); ``` -------------------------------- ### PubkyAppUser Profile Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents a user's profile information. This model includes fields for name, bio, profile image, links, and status. ```APIDOC ## GET /pub/pubky.app/profile.json ### Description Retrieves a user's profile information. ### Method GET ### Endpoint /pub/pubky.app/profile.json ### Parameters #### Query Parameters - **user_id** (string) - Required - The unique identifier for the user. ### Response #### Success Response (200) - **name** (string) - User's name. - **bio** (string) - Short biography. - **image** (string) - URL to the user's profile image. - **links** (array) - List of associated links (title + URL). - **status** (string) - User's current status. ### Response Example ```json { "name": "Alice", "bio": "Toxic maximalist.", "image": "pubky://user_id/pub/pubky.app/files/0000000000000", "links": [ { "title": "GitHub", "url": "https://github.com/alice" } ], "status": "Exploring decentralized tech." } ``` ``` -------------------------------- ### Compare JavaScript Unicode Length Methods Source: https://github.com/pubky/pubky-app-specs/blob/main/docs/UNICODE_NOTES.md Use `[...str].length` or `Array.from(str).length` to count Unicode code points, matching Rust's `.chars().count()` behavior. Avoid `str.length` as it counts UTF-16 code units and can incorrectly reject valid input with characters outside the Basic Multilingual Plane. ```javascript const str = "Hi🔥"; // ❌ WRONG - counts UTF-16 code units, not Unicode code points str.length // 4 (will reject valid input) if (username.length > MAX_USERNAME_LENGTH) { showError("Username too long"); } // This would incorrectly reject "🔥".repeat(25) // because JS sees 50 code units, but Rust sees 25 code points (valid!) // ✅ CORRECT - counts Unicode code points (matches Rust) // These methods correctly handle characters outside BMP (emoji, etc.) [...str].length // 3 (Unicode code points) - counts 🔥 as 1 Array.from(str).length // 3 (also works) ``` -------------------------------- ### PubkyAppFollow Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Represents a follow relationship between users in the Pubky application. ```APIDOC ## POST /pub/pubky.app/follows/:user_id ### Description Establishes a follow relationship for a user. ### Method POST ### Endpoint `/pub/pubky.app/follows/:user_id` ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to follow. #### Request Body - **created_at** (integer) - Required - Timestamp of creation. ``` -------------------------------- ### PubkyAppPost Collection Content Structure Source: https://github.com/pubky/pubky-app-specs/blob/main/README.md Defines the typed JSON envelope used for 'collection' kind posts, including its fields and validation rules. ```json { "name": "AI papers", "description": "Best stuff", "cover_image": "pubky://userA/pub/pubky.app/files/0034A0X7NJ52C", "items": [ "pubky://userA/pub/pubky.app/posts/0034A0X7NJ52A", "pubky://userB/pub/pubky.app/posts/0034A0X7NJ52B" ] } ``` -------------------------------- ### Rust WASM Validation Logic Source: https://github.com/pubky/pubky-app-specs/blob/main/docs/UNICODE_NOTES.md Illustrates the core validation logic within the Rust WASM module, focusing on character count validation against a defined maximum length. This ensures consistent handling of Unicode characters. ```rust const MAX_USERNAME_LENGTH: usize = 50; fn validate(&self, _id: Option<&str>) -> Result<(), String> { let name_length = self.name.chars().count(); // Unicode code points if name_length > MAX_USERNAME_LENGTH { return Err("Validation Error: Invalid name length".into()); } Ok(()) } ``` -------------------------------- ### Parse Pubky URI Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Use the `parse_uri` function to convert a Pubky URI string into a structured object. Handle potential errors with a try-catch block. ```javascript import { parse_uri } from "pubky-app-specs"; try { const result = parse_uri("pubky://userID/pub/pubky.app/posts/postID"); console.log(result.user_id); // "userID" console.log(result.resource); // e.g. "posts" console.log(result.resource_id); // "postID" or null } catch (error) { console.error("URI parse error:", error); } ``` -------------------------------- ### Access Validation Limits via WASM Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md Retrieve validation limits using WASM accessors, either directly or through the PubkySpecsBuilder. ```javascript import { PubkySpecsBuilder, getValidationLimits } from "pubky-app-specs"; const limitsFromWasm = getValidationLimits(); const builder = new PubkySpecsBuilder("pubky_id_here"); const limitsFromBuilder = builder.validationLimits; ``` -------------------------------- ### Parsing a Pubky URI Source: https://github.com/pubky/pubky-app-specs/blob/main/pkg/README.md The `parse_uri()` function converts a Pubky URI string into a strongly typed object. ```APIDOC ## `parse_uri(uriString)` Converts a Pubky URI string into a strongly typed object. ### Parameters #### Path Parameters - **uriString** (string) - Required - The Pubky URI string to parse. ### Returns A `ParsedUriResult` object with: - **user_id:** The parsed user identifier. - **resource:** A string indicating the resource type. - **resource_id:** An optional resource identifier. ### Request Example ```js import { parse_uri } from "pubky-app-specs"; try { const result = parse_uri("pubky://userID/pub/pubky.app/posts/postID"); console.log(result.user_id); // "userID" console.log(result.resource); // e.g. "posts" console.log(result.resource_id); // "postID" or null } catch (error) { console.error("URI parse error:", error); } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.