@places2play/sdk
v0.1.1
Published
Official Places2Play API client — typed, framework-agnostic access to the paid GraphQL API (server-side OAuth client-credentials + browser-safe domain-locked publishable keys), plus a thin embed-map loader.
Maintainers
Readme
@places2play/sdk
Official, typed TypeScript client for the Places2Play paid GraphQL API.
- Server — OAuth 2.0 client-credentials with a secret key (auto token mint/refresh).
- Browser — a domain-locked publishable key (
pk_api_…), read-only, safe in page code. - Embed — a thin loader (
mountMap) for the canonical embed map widget.
This release exposes read operations only. Framework-agnostic core (Node / edge / Deno /
Bun and the browser), dual ESM + CJS with .d.ts, tree-shakeable, zero runtime deps.
API usage is governed by the Places2Play API terms (ephemeral cache only, no bulk/enumeration sweeps, attribution, canary integrity). See
docs/api-license.md. The MIT license on this package covers the client code only.
Install
npm install @places2play/sdkRequires Node ≥ 18 (for built-in fetch; pass your own fetch otherwise).
Get a key
Create credentials at https://places2.org/developers (an active subscription is required — there is no free API tier). You get:
- a secret OAuth client (
client_id=p2c_…+client_secret) for server use, and/or - a publishable browser key (
pk_api_…) locked to the domains you register, for browser use.
Server usage (secret client-credentials)
import { Places2Play } from '@places2play/sdk';
// SERVER ONLY — never ship the secret to a browser.
const p2p = new Places2Play({
clientId: process.env.P2P_CLIENT_ID!,
clientSecret: process.env.P2P_CLIENT_SECRET!,
// host defaults to https://places2.org; tenantSlug defaults to "places2play".
});
// Token mint/refresh against /api/oauth/token happens automatically.
const page = await p2p.places.search({ state: 'CA' }, { first: 20 });
// Paginate the Connection/edges cursor pattern for you:
for await (const place of p2p.places.nearby({ latitude: 37.77, longitude: -122.41, radiusKm: 50 }).all()) {
console.log(place.name);
}
const groups = await p2p.tags.groups();
const station = await p2p.weather.station(123);The constructor throws in a browser (it detects window) so a secret can't leak client-side.
Browser usage (publishable, domain-locked key)
import { Places2PlayBrowser } from '@places2play/sdk';
// Safe to ship: the key only works from the domains you registered for it.
const p2p = new Places2PlayBrowser({ publishableKey: 'pk_api_…' });
const { edges } = await p2p.places.search({ query: 'pickleball', state: 'TX' });The key is enforced server-side against the browser-set Origin (then Referer) — values page
JS cannot forge. A leaked key is useless off the allow-list. The browser client is read-only and
never calls the token endpoint.
Embed map (thin loader)
import { mountMap } from '@places2play/sdk/embed';
const map = await mountMap('#map', { key: 'pk_embed_…' }); // lazy-loads embed.js
map.addMarkers([{ lat, lng, title }]);
map.on('placeClick', (p) => openSidebar(p));mountMap just injects the canonical https://places2.org/embed.js and calls
window.Places2Embed.init; the real widget logic stays server-versioned. Uses a publishable
pk_embed_… key (domain-locked), not the API key.
Read operations
| Area | Method | GraphQL field |
| --- | --- | --- |
| Places | places.get(id) | place |
| | places.search(search?, pagination?) | places |
| | places.nearby(input) | nearbyPlaces |
| | places.statistics() | placeStatistics |
| Tags | tags.groups() | tagGroups |
| | tags.icons() | icons |
| Weather | weather.station(id) | weatherStation |
| | weather.stations(bounds?, pagination?) | weatherStations |
| | weather.nearbyStations(input) | nearbyWeatherStations |
| | weather.history(stationId, days?) | weatherHistory |
| | weather.statistics() | weatherStatistics |
| Meta | meta.apiInfo() | apiInfo |
The bundled schema.graphql is the exact SDL the SDK targets; a contract test keeps the SDK's
operations and field selections in lock-step with the server (see Contract guard).
Errors
All failures throw typed errors (never raw GraphQL arrays):
P2AuthError— 401/403 (invalid/expired credentials,insufficient_scope).P2QuotaError— 429quota_exceeded(carriesplan,monthlyQuota,upgradeUrl). Never auto-retried.P2RateLimitError— 429 short-window limit (carriesretryAfterSeconds).P2ValidationError— 400 / in-band query errors.P2ServerError— 5xx / transport failures.P2ConfigError— SDK misuse (e.g. a secret passed to the browser client).
Retry is opt-in and never crosses a hard quota cap:
const p2p = new Places2Play({
clientId, clientSecret,
retry: { maxRetries: 2 }, // transient 429 rate-limits + 5xx only
onQuota: (info) => console.warn('quota', info),
onRateLimit: (secs) => console.warn('retry after', secs),
});Pagination
places.search and weather.stations support cursor pagination. The returned query is awaitable
(first page) and iterable:
const firstPage = await p2p.places.search({ state: 'CA' });
for await (const place of p2p.places.search({ state: 'CA' }).all()) { /* every place */ }
for await (const page of p2p.places.search({ state: 'CA' }).pages()) { /* each Connection */ }Please respect the no-bulk-enumeration rule in the API terms.
Contract guard
src/__tests__/schema-contract.test.ts asserts that the bundled schema.graphql matches the app's
canonical SDL, that the SDK exposes exactly the server's full set of read (Query) fields and no
mutations, and that every operation document validates against the schema. A server schema change
breaks this test loudly. Regenerate after an intentional schema change:
# in volumes/react: regenerate the canonical SDL snapshot
npx ts-node --compiler-options '{"module":"commonjs"}' scripts/gen-graphql-sdl.ts
# in packages/sdk: pull it in + re-run the guard
npm run sync-schema && npm testVersioning & stability
- SemVer. The SDK follows Semantic Versioning. While
0.y.z, the surface may still change between minors; from1.0.0the public API is stable. - Additive-only read contract. The public GraphQL read contract only grows: new fields
are added as nullable/optional, and nothing is removed or renamed without a major.
This is enforced in CI — the server diffs the live schema against a frozen baseline with
findBreakingChanges, and the SDK's bundledschema.graphqlis diffed against the live SDL — so an older installed SDK keeps working against an evolved API. - API version header. Every request sends
X-Places2-Api-Versionso future server changes can be negotiated without breaking existing clients. - Deprecation policy. Supported: the latest minor plus one behind. Deprecations are
announced in
CHANGELOG.mdand vianpm deprecatewith at least 6 months notice before a breaking removal. SeeCHANGELOG.mdfor the history.
Develop / build
npm install
npm run typecheck # tsc --noEmit
npm test # vitest
npm run build # tsup → dist (ESM + CJS + .d.ts)Publishing (owner / CI only)
The @places2play npm scope is not yet claimed — do not publish until it is. When ready:
- Claim the scope:
npm org create places2play(or via the npm website). - Authenticate:
npm login --scope=@places2play(or a granular automation token in CI). npm publish --dry-runthennpm publish --access public.
prepublishOnly runs build + test first. publishConfig.access is public and the files
allowlist (plus .npmignore) ships only dist/, schema.graphql, README.md, and LICENSE.
See docs/API-SDK-PLAN.md §4 for the recommended tag-triggered GitHub Actions release with npm
provenance.
