Primitives

pagelove/primitives.mjs is the low-level HTTP client that pagelove.mjs uses internally. Most apps do not touch it directly.

When to reach for it

PLDocument and PLElement are DOM-based wrappers. The inspected module uses browser facilities such as window, document, Node and DOMParser; discovery and lazy tag loading also use document events and IntersectionObserver. A plain build script, service worker or command-line runtime is not a drop-in environment for these examples. Use the documented HTTP interface directly outside a DOM environment, or explicitly provide and verify a DOM adapter and compatible module loading. This guide does not supply that adapter.

For everything else, use the Pagelove class and the declarative flow on top.

Loading the library

<script type="module">
  import { PLDocument, PLElement } from 'https://pagelove.github.io/beta-js/pagelove/primitives.mjs';
</script>

The module exports two classes: PLDocument and PLElement.

The PLDocument class

A PLDocument represents a Pagelove resource URL and the live DOM associated with it.

Constructor

Form Bound document
new PLDocument() window.location.href — bound to window.document
new PLDocument(url) The given URL. If it matches window.location.href, the live document is bound; otherwise the document is fetched and parsed lazily.

Methods

Method Description
OPTIONS() Issues an OPTIONS request with Accept: multipart/mixed, parses the multipart response, and dispatches a PLCapability event on every node matching a declared selector.
createElement(element) Returns a new PLElement wrapping the given DOM node.
req(method, ...opts) Returns a bare Request targeting the document URL.

Properties

Property Type Description
url string The URL this document is bound to.
document Promise<Document> Resolves to the bound DOM document. Fetches and parses the HTML on first access if no live document is bound.

A PLDocument bound to a live Document stores a WeakRef to itself on document.pagelove and installs listeners for PLCapability and PLMethodCompleted.

The PLElement class

A PLElement wraps a single DOM node and knows how to issue HTTP requests scoped to that node.

Constructor

Form Effect
new PLElement(url) Creates an element bound to the URL with no DOM node attached yet.
new PLElement(url, element) Binds to the given DOM node. The element's ownerDocument becomes the associated document.

Methods

Method Description
GET() Requests the generated selector range. For a response with response.ok, parses the body as one HTML node and returns that node. Does not validate the fragment response contract or return the raw Response; see GET results and failures.
PUT(body?) Replaces the element on the server. Body defaults to element.outerHTML; a Node body is serialized via outerHTML. Returns the raw Response.
POST(body) Posts a child fragment. The response body is parsed as a single HTML node and appended as a child of the wrapped element (unless the supplied body was already a live attached node). Throws if no body is supplied.
DELETE() Deletes the element on the server and removes it from the DOM on success.
req(method, opts) Builds the underlying Request object — sets the Range header, conditionally sets If-Match, and merges the caller's opts.

GET results and failures

The inspected GET() helper checks response.ok, not specifically 206 Partial Content, the expected Content-Range, or the response's HTML media type. A successful response that parses as one node is not proof that it contains the requested fragment: an unexpected 200 OK body can also pass that check. Verify the actual GET response contract before accepting the result as the intended target.

The parser trims the body and parses it through an HTML template. It requires exactly one top-level child node; an empty body or multiple top-level nodes causes rejection. That child can be a text or comment node, so a returned Node is not necessarily an Element with the expected identity. The returned node is separate from the wrapped node; GET() does not replace the displayed content automatically.

Network and parsing failures reject the promise. In the captured module, the non-success response branch also refers to responseText outside the block where it is declared, so that branch can reject with a ReferenceError rather than the intended thrown Response. Do not assume a caught value exposes the HTTP status or response body. Catch failures without accepting the returned content or treating them as an empty result, a permission decision, or proof that the target does not exist. This is a finding from the captured client source, not a live server/browser verification; verify the selected client revision before relying on its error contract.

When the application needs to inspect the raw status, headers and body before parsing, use the HTTP interface directly. A wrapper's req('GET') builds a Request that can be passed to fetch(), but that direct call does not run the helper's lifecycle events or response-ETag update. The application must handle request options, response validation and errors itself; neither constructing the request nor dispatching it proves server authorization or the intended source/view mapping.

Properties

Property Type Description
url string The document URL the element is scoped against.
element Element The wrapped DOM node. Setting it also sets document from the node's ownerDocument.
document Document The DOM document the wrapped element belongs to.
selector string Computed from the wrapped element's current DOM. The inspected module prefers its id, otherwise anchors to an ancestor ID when available and uses locally unique itemprop child steps or positional :nth-child(...) steps. Class and role fallbacks are not implemented; generation errors can return a bare tag selector.

A generated selector is a current DOM address, not a durable entity identifier. Positional steps can change meaning when siblings are inserted, removed or reordered; a page-only view ID may also differ from the stored source's identity. Prefer stable, unique source IDs and verify the actual mutation target and supported source/view mapping before writing. Keep the intended target with a pending request rather than silently regenerating a different address after structural changes.

OPTIONS lives on PLDocument, not PLElement — discovery is document-level.

Attached methods on DOM elements

PLDocument listens for PLCapability events on its bound document. The event payload looks like:

{
  selector: '<css selector>',
  allow: ['GET', 'PUT', 'POST', 'DELETE']
}

For each method named in allow, the document constructs a PLElement for the event target and attaches the matching method directly to the DOM node as a non-writable, configurable property:

Object.defineProperty(target, 'PUT', { value: plElement.PUT.bind(plElement), ... });

When discovery and event handling successfully attach wrappers, methods such as element.GET(), element.PUT(body), element.POST(body), and element.DELETE() can be called on the DOM node without further imports. Attachment follows local PLCapability event data; it is not an authorization grant, and page scripts can also construct such events. The server still decides each request against current policy and applicable conditions. See OPTIONS discovery boundaries before treating an attached method as permission to act.

ETag handling

ETags are loaded lazily, only for elements that need them.

This is the inspected client's path/query/fragment heuristic, not proof of the actual server origin or durable child identity. Retain the original reviewed baseline and pending target/body separately from mutable helper state, and verify the returned representation before a later conditional write.

Request format

Every request a PLElement issues is built by req(method, opts):

Header Value When
Range selector=<generated-selector> Always
If-Match <element.etag> When element.etag is a string and the method is not POST

Everything else is a standard fetch() Request. Each request also dispatches PLMethodStarted before sending and PLMethodCompleted after the response arrives. Both events bubble and carry { method, selector }; PLMethodCompleted additionally carries response.

Examples

Calling an attached method

<script type="module">
  import { PLDocument } from 'https://pagelove.github.io/beta-js/pagelove/primitives.mjs';

  const doc = new PLDocument();
  await doc.OPTIONS();

  document.addEventListener('click', async (event) => {
    const card = event.target.closest('article.note');
    if (card && typeof card.DELETE === 'function') {
      await card.DELETE();
    }
  });
</script>

In this example, the function-presence check tests whether a wrapper was attached to the local card. It does not confirm current permission, the server target's existence or successful persistence. Handle the actual request outcome using the selected client version's result contract; an attached wrapper can remain present after the policy changes.

Manual PLDocument and PLElement

<script type="module">
  import { PLDocument } from 'https://pagelove.github.io/beta-js/pagelove/primitives.mjs';

  const doc = new PLDocument('/notes.html');
  const target = document.getElementById('note-42');

  const note = await doc.createElement(target);
  await note.PUT('<article id="note-42">Edited</article>');
</script>

The wrapper is constructed by hand and no capability discovery is required. Range: selector=#note-42 is generated from the element's id; If-Match is added automatically once note.element.etag is populated.

See also