Pages

Plugin Apps

A plugin app is a Pebble app plugin of your own, built with the framework. It has no watch code. It runs in the Pebble app on the phone and serves data to every watchface that reads its kind of data, not only yours. Pebble App Plugins covers the other side, a face reading a plugin.

Plugins are still a Core Devices preview in the Pebble app, which keeps them off until the wearer turns them on under Settings, Plugins, Plugins / permissions preview. A plugin app publishes to the appstore with pebble publish like any other app. Building one needs Pebble SDK 4.44 or later and pebble-tool 5.1.2 or later.

What One Looks Like

A plugin app is a face folder whose appinfo says it is a plugin. A repo of them keeps each one as a unit under plugins/, which paf finds the way it finds watchfaces/ and watchapps/, and each one pins framework 6 or later.

plugins/calendar-ical/
  paf.config.json       the framework tag and the plugins the unit lists
  package.json          with workspaces: ["paf", "paf/plugins/*"]
  pebble.appinfo.json   with "projectType": "plugin"
  src/plugin/index.ts   the plugin's script, where it starts
  src/config/index.ts   its settings page, when it has one

The Appinfo

{
  "name": "calendar-ical",
  "displayName": "Calendar Enhanced + iCal",
  "uuid": "…",
  "version": "1.0.0",
  "sdkVersion": "3",
  "projectType": "plugin",
  "configPage": "config.html",
  "usesPermissions": [{ "name": "Calendar", "reason": "To merge your phone's calendars", "required": true }],
  "plugin": { "description": "…", "sources": [ … ] }
}

The plugin block is the Pebble SDK's own, and goes into the pbw as written. A plugin app's usesPermissions go in as written too, each with its reason and required flag, where a face's are worked out from its keys. The build writes the plugin's script as plugin.js and its settings page as config.html, so a plugin block naming another script, or a configPage other than config.html, is refused. "configPage": "config.html" is what builds the settings page, so a plugin app without it gets no page, even with a src/config/index.ts.

A plugin app has no watch code, so the fields only watch code uses are refused, naming the field: messageKeys, resources, defines, textDefines, providers, targets, watchapp, watchface, menuIcon, targetPlatforms, and enableMultiJS. The build also refuses a projectType other than plugin or native, which is what pebble new-project writes for a watchface, so a misspelled plugin app does not build as a face. A plugin app has no features and no message keys, so the build reads no features from it and fills in none of the fields it fills in for a face, as The Fields the Build Fills In covers. Its sdkVersion and any capabilities go in as the appinfo writes them.

The Build

paf build <plugin app> writes the plugin app's sandbox under targets/, bundles its script into plugin.js, builds its settings page into config.html, and runs pebble build there. It runs none of a face's phone build, settings page check, or header. The sandbox gets the SDK's own plugin wscript, which builds no watch code. With no watch code there is nothing for the dev plugin's dev mode to change, so --dev stops the build.

The script is bundled with esbuild from src/plugin/index.ts into one file, since the Pebble app loads a plugin's script as one. It imports the framework by relative path from paf/, as a face does, and everything it reaches goes into the bundle. The framework's iCal reader brings ical.js with it, with its MPL licence header kept at the top of its part of the bundle, and a build stops on an ical.js that does not open with that header rather than shipping without it. The bundle targets ES2017, the plugin runtime has fetch but no timers and no XMLHttpRequest, and esbuild's warnings print with the build.

The Settings Page

A plugin app's settings page is a Clay page, written as a Clay config the way a face writes one. src/config/index.ts exports clayConfig, and can export a customClay written with the function keyword. It is bundled the way the script is, so its imports resolve the same way.

The page's storage is not the plugin's, so the page asks the plugin for the saved settings when it opens and hands them back on Save, and the plugin keeps them. The build adds what that takes:

  • The Framework's Page Code runs ahead of the plugin's customClay, after the framework's show and hide for visibleWhen rows. It loads the saved settings once the plugin is ready, and turns Save on only once they have loaded, so a page still on its defaults cannot save over the wearer's. Save closes the page only when the plugin answers that it kept them.
  • A Status Row sits above the Save button, where a load or a save that fails, or that the plugin has not answered after five seconds, says why.
  • A Save Button goes at the foot of a page with none.

A row that names watch capabilities is refused, since a plugin's page opens with no watch behind it.

src/config/index.ts can also export components, the Clay components its rows need beyond Clay's own, the way a face passes components to startPebbleApp. The build registers them after the framework's page rules, and stops on a row that no component draws, or a row with no type, since Clay would leave the page blank at that row. The framework's location search is one, for a locationsearch row:

import locationSearch from '../../paf/ts/clay/location-component';

export const components = [locationSearch];

The build brings Clay's own text box with the search on a page that has none, for its look, as The Location Search covers, and Clay's own select with a themePreview row on a page that has no select, the same way a face's page gets them. A plugin app that exports its own text box or select keeps it. The search asks Open-Meteo for its places, so a plugin app with one lists open-meteo.com under Internet in its usesPermissions. The search calls geocoding-api.open-meteo.com for places, and a field marked timeZone: true also calls api.open-meteo.com for a place's time zone, so listing the hosts a page's searches call by name works as well, and so does an Internet entry naming no site. On Android the Pebble app holds the page to the sites listed there, so the build stops on a search whose plugin app does not reach the geocoder, or the forecast host when a row takes a zone, and names the one left off. A search row with no messageKey stays out of the saved settings, and page code reads the pick with the row's get when the row fires change.

On the plugin side, handleSettings from ts/plugin-app/settings.ts answers the page, and readSettings reads the settings back in a source handler:

import { handleSettings } from '../../paf/ts/plugin-app/settings';

const OPTIONS = { secret: ['FEED1_URL'], defaults: { REFRESH: '30' }, refresh: ['calendar/event'] };

handleSettings(OPTIONS);

A key marked secret, such as a private iCal link, goes to Pebble.secureStorage, which the phone encrypts and only the plugin can read, and the rest go to localStorage. A save writes the secrets first, so one that fails leaves the other settings as they were, and then has the Pebble app read the sources in refresh again. A secret that cannot be read fails the page's load, so the next save cannot delete it, and keeps its default in a source handler. ts/plugin-app/runtime.ts types the plugin runtime's Pebble through pluginPebble().

The plugin runtime takes one config handler, and handleSettings registers it, so a plugin app that answers messages of its own or acts on a save passes hooks as the fourth argument:

handleSettings(OPTIONS, pluginPebble(), localStorage, {
  onMessage: (type, message, respond) => {
    if (type === 'my-plugin-status') {
      respond({ status: 'ok' });
    }
  },
  onSaved: (before, after) => {
    if (before.REFRESH !== after.REFRESH) {
      console.log('the refresh changed');
    }
  },
});

onMessage hears every message that is neither the load nor the save, with its type, and answers it through respond before it returns or before its promise settles. A message it does not reply to in that time gets the error handleSettings gives a message it does not know, so the page is never left waiting, and a respond from a callback after that is only logged. Only the first reply reaches the page, so a hook that replies and then throws is logged rather than answered twice.

onSaved hears a save once it is kept, with the settings before and after it. Each holds the defaults under what was saved and leaves out every secret key, a key saved in plain storage before it was marked secret included. The hook runs, and its promise settles, before the page hears the save as kept, since the Pebble app ends the plugin's run as soon as the page is answered and a hook still running then, such as one deleting pins, may never finish. The Pebble app reads the sources again after the hook, so a run it starts sees what the hook did. The plugin runtime has no timers, so nothing cuts a slow hook short. The page gives up on a save after about five seconds and says the plugin has not answered, though the settings are already kept, so keep the hook's work well inside that. A hook that never settles holds every later save in that run the same way, kept but never answered, with its hook never run and the sources never read again. Saves are kept one at a time and their hooks run one at a time, in the order the saves came in, so a second tap while a hook is still running waits its turn and hears the settings its own save changed. An onSaved that throws or rejects is logged, and the page still hears the save as kept.

Page code of a plugin app's own, written into the page by customClay beside the framework's, takes the Clay page's types with import type { ClayPage, ClayPageRow, PluginPageBridge } from '../../paf/ts/plugin-app/page-types'. A type-only import compiles away, so nothing is left for the page to load.

paf tool <plugin app> clay-preview builds the same page for a desktop browser. A stand-in for the Pebble app loads the values a --settings file holds, and a Save shows in the console what it would have sent.

Reading the Wearer's Preferences

ts/plugin-app/preferences.ts reads the wearer's units, clock, and locale from the built-in Preferences plugin's preferences/units, BUILT_IN_PREFERENCES, by its uuid, which asks for no permission. readPebbleAppPreferences(pebble, overrides) answers units, clock as 12h or 24h, and locale, such as en-GB, each null where the reply names none. A clock is read whatever its case. A refused read answers no preferences and the reason. preferencesFrom(envelope, overrides) reads the same from an update the Pebble app pushes.

pebbleAppUnits(pebble, overrides) reads the units alone and puts the plugin's own choice over each one, where app, or a choice that is not one of the Pebble app's own units, follows the Pebble app. Units the Pebble app does not give are °C, km/h, and hPa, so serving always has a unit to send. readPebbleAppUnits(pebble, overrides) reads the same units for a caller that has to tell the Pebble app's own from the defaults, such as a settings page showing them: a refused read answers units null and the reason, and a reply that names none answers null and NO_UNITS.

Serving Calendar Events

ts/plugin-app/calendar.ts serves the framework's CalendarEvents as the standard calendar/event source, in the shapes the Pebble app's built-in Calendar plugin uses, so every face that reads the built-in reads a plugin app the same way. eventInstance(event, instanceId) makes one instance. The texts go out as both shortText and longText, apart from the end's label, which is shortText only, as the built-in sends them. The start and end each carry a label beside their timestamp, the time on the phone's clock as HH:MM or All day, and a blank location is left out. An event's description goes out as a longText only, cleaned as plainDescription in ts/calendar/description.ts cleans it, and blank notes are left out, as the built-in leaves them.

Short Labels. The built-in's HH:MM reads the same for an event today and one next week. eventInstance(event, instanceId, offsetAt, labels) takes { style: 'short', nowSeconds, clock, locale } as its last argument for labels that name the day. A start on the phone's today reads its time, 2:30p on a 12h clock, whatever its case, and 14:30 on any other, with midnight as 12:00a and noon as 12:00p. One to six days ahead reads the short weekday, such as Thu, and any other day, a past one included, the date, such as Nov 27. The longText adds the time after the day, as Thu 14:30. The end is counted from its start's day, so an end on the same day reads its time, and so does one at the midnight that closes it, as 00:00. One on a later day takes the weekday or the date by the same rule as a start. A meeting tomorrow from 14:00 to 15:00 reads Thu and 15:00. An all-day event keeps All day. The days are the phone's, counted on its calendar, so a week holding a clock change still names the right ones.

The weekday and the date come from Intl in the locale given, in the locale's own order and with its own separators, so en-US reads Nov 27, en-GB 27 Nov, and Japanese 11月27日. They are read on the Gregorian calendar whatever the locale's own, asked for by option and in the tag as -u-ca-gregory for an older engine, so a Persian phone reads February rather than Bahman. A tag such as fr_FR is read as fr-FR. Each name is made to fit a shortText first. A trailing full stop goes, so French sept. reads 27 sept, and a Latin or Cyrillic name still too long is cut. A weekday is cut to four letters. A month is cut to whatever room the locale's own separators leave beside a two-digit day, so Canadian French juill. reads 27 juil, German 28. Sept. reads 28. Sep, and Hungarian szept. 28. reads sze 28.. A cut never leaves fewer than three letters, so a locale with less room, such as Brazilian Portuguese with its 28 de , is named in English. A name in another script is never cut, since a cut there can leave a mark hanging off its last letter. The names are decided once per locale. If any of the seven weekdays or twelve months still does not fit beside a two-digit day, or the cut leaves two the same, as Swahili's weekdays all cut to Juma, the whole locale is named in English, as Thu and Nov 27, so a label never mixes two languages. A runtime with no Intl locale data names everything in English too, without building a formatter, since building one there runs the script out of memory. Pass nowSeconds from the run, since the labels never read the clock, and clock and locale from readPebbleAppPreferences. Left out, clock is 24h and the names are English. { style: 'builtIn' }, the default, sends the built-in's labels.

CALENDAR_EVENT_SOURCE is the source's declaration. The appinfo is JSON, so copy it into the plugin block's sources as written. The Pebble app drops any property or shape the block does not declare, and nothing checks the copy, so a spec comparing the two keeps them together. It asks Calendar of its callers, which the Pebble app requires of a plugin that reads the phone's calendars through the built-in.

An all-day event goes out from UTC midnight of its first day to UTC midnight after its last, as the built-in sends one on Android, and a face's reader rounds that to the phone's own midnight. On a phone at UTC+13 or further east, such as New Zealand in summer, UTC midnight is past local noon, so an all-day event reads a day late there, as the built-in's own do.

CalendarEvent carries a feed's uid from the iCal reader and a calendar's name from the plugin reader, for a plugin that merges several sources. Every occurrence of a repeating event shares its series' uid, so the uid and the start together pick out one meeting. The iCal reader also marks an event free, tentative, or declined, and reads its notes, each when asked, as The Calendar Store covers. The plugin reader keeps the description an update carries, cleaned the same way. A plugin serving more events than a watchface shows passes maxEvents to parseIcal, up to SOURCE_LIMIT_MAX in ts/plugin-app/source-limit.ts, the 200 a limit can ask for. A face's subscription asks for CALENDAR_PROPERTIES, which leaves the notes out, since the watch never shows them. A plugin app reading the built-in to serve its events on with their notes asks for CALENDAR_PROPERTIES_WITH_DESCRIPTION from ts/plugin-sources/calendar.ts, since the built-in sends description only to a read that names it or names no properties.

matchesKeyword(title, keywords) in ts/calendar/keywords.ts says whether a title matches any of a comma-separated list the wearer types, or a list of keywords, for a plugin that hides or marks events by their titles. Case is ignored, empty entries and the spaces at the ends are dropped, and a keyword matches where it starts a word and runs on from there, so Lunch matches "Team Lunch" and "Lunchtime walk" but not "Brunch". keywordMatcher(list) prepares the list once and hands back a function that checks a title, for a caller checking many titles against it, and matchesKeyword goes through it. parseKeywords(list) reads the list into its keywords.

Serving Stock Quotes

ts/plugin-app/stocks.ts serves the framework's StockQuotes as finance/stock, modelled on Pebble's own Stocks plugin, with properties of our own added. stockInstance(quote, instanceId, extras) writes Pebble's five properties, ticker, name, price, day_change, and day_change_percent, in exactly Pebble's text, such as $187.42, $187.42 +0.52% for the long price, -$1.20, and +0.52%, so a face written against Pebble's reads a plugin app with no change. A quote from a provider that sends no currency, such as Finnhub, goes out with no sign. A price in pence stays GBp, written as its code. Pebble's works the day's change out from Yahoo's previousClose, while the framework's Yahoo provider uses chartPreviousClose, so the two can differ by a little on the same ticker.

On top of Pebble's five, an instance carries the price and both changes as numbers, the quote's currency code, when the quote is from as updated, and the source and market a plugin passes in extras. The source goes out whole in its longText and cut to 7 characters in its shortText, such as AlphaV for Alpha Vantage and 12Data for Twelve Data. The status words, such as RATE LIMIT, and the market state postclose run past 7 and go out whole, since a face matches on the word, so the Pebble app logs a warning for them. A ticker with no price goes out with its ticker, its name, and its status word in status, such as NO ACCESS, rather than being left out. A face reading only Pebble's five properties shows its own dash for the missing price.

STOCK_SOURCE is the source's declaration, to copy into the plugin block's sources as written.

Serving the Weather

ts/plugin-app/weather.ts serves a WeatherReading from the weather providers' fetchReading as the standard weather/location, modelled on the Pebble app's built-in Weather plugin. WEATHER_LOCATION_SOURCE is the source's declaration, to copy into the plugin block's sources as written. Its standard properties are the built-in's, in the built-in's shapes without icon and image, and its extras are Weather+'s. Every series is named hourly_ or daily_, and nothing else is.

weatherLocations(pebble) reads the wearer's places from the built-in Preferences plugin, BUILT_IN_PREFERENCES, by its uuid, and subscribes to them so the Pebble app runs the plugin again when the list changes. It hands back each place's key, name, coordinates, and whether it is the current location, in the wearer's order, and leaves out a place with no coordinates, such as a current location with no fix yet. A read the Pebble app refuses hands back no places and the reason. listWeatherPlaces(pebble) reads every place in the list, a current location with no fix included, for a caller that has to show or keep the whole list, such as a settings page. Each place comes back in the wearer's order with its key, name, whether it is the current location, and located, which is true for a place with coordinates, and such a place carries them. An instance with no key is left out, and one with a key and no properties yet, such as a current location still being set up, comes back with an empty name and located false. It makes no subscription unless it is passed { subscribe: true }. listedPlacesFrom(envelope) reads the same list from an update the Pebble app pushes, and fetchablePlaces(listed) keeps the ones with coordinates, in order and without located, as weatherLocations hands them back. A refused read answers no places and the reason. A refusal that names no reason at all, or only a code of 0, answers NO_REASON from listWeatherPlaces, weatherLocations, and the preferences reads. failureReason(error) in ts/plugin-app/runtime.ts gives the same words for a plugin app's own reads, so a refusal reads the same wherever it came from. The wearer's units come from Reading the Wearer's Preferences.

locationInstance(reading, place, units, asked, nowMs) turns one place's reading into its instance, under the place's key. It sends every single value, and each series only when asked names it, or every series when the request names none, as the built-in does. Temperatures go out in °C or °F, wind in km/h, mph, m/s, or knots, and pressure in hPa or inHg, each with its unit and a short text. A shortText keeps to 7 characters, SHORT_TEXT_MAX in ts/plugin-app/short-text.ts, since the Pebble app warns on a longer one and the tight spots that read it cut it off. A temperature reads 24°C and a wind 12 km/h in the built-in's style, with knots as kn and the space dropped from a wind of 100 or more. A pressure's shortText is its number alone, such as 1016 or 30.01, since the unit rides beside it, and its longText carries the unit. A place's name is left as long as it is, as the built-in sends it. condition, hourly_condition, and daily_condition carry the sky in short words of 7 characters or fewer in shortText, such as Pt Cldy or T-Storm, from SHORT_LABELS. Their longText carries more words: the framework's full words for condition, and for the series the same words where they fit in 12 characters, or a shorter form from PHRASE_LABELS where they do not, such as Partly Cldy. The Pebble app builds the watch's own weather from them: its short phrases from the current sky's shortText, cut at 12 and 22, its long phrase from that sky's longText, cut at 32, and each day's phrase from daily_condition's longText, cut at 12. condition_code is one of the standard's nine codes from CONDITION_CODES, and weather_code and its series carry the WMO code. utc_offset is in minutes east of UTC, and uv_index is the day's peak, both as the built-in sends them. The series keep the reading's stamps, so a reader places each point by its time, as Fetching the Weather covers. source names the provider, cut to fit in its shortText, such as OpenMet, OWM, or WxAPI, and whole in its longText, and updated carries when the reading is from with its time on the phone's clock. latitude and longitude are the place's own coordinates, from the lat and lon the place is given, to four decimals, about 11 m, which is as fine as a weather place needs. The numericValue and the longText carry all four, and the shortText two, such as -112.50. They are the one exception to sending every single value: they go out only to a request that names them, since only a face that wants the wearer's place should get it, and only as a pair of real coordinates. The Pebble app's own reader takes an instance without them. hourly_pressure is the pressure at sea level, like pressure, where Weather+'s series of the same name is the pressure at the ground.

Stamping a Run. Each fetchReading takes an optional last argument, onSend, which hears each request as it goes out, before it is sent. It names the provider as source, how many calls the request counts as, and the weight of each: the Open-Meteo batch as openmeteo with one call for each place in it at READING_WEIGHT, and each place's call to OpenWeatherMap or WeatherAPI.com under its own name, as one call of weight 1. Stamp the ledger there. The hook can hand back a function, which hears the request's error once it answers, so a request that answers NETWORK_ERROR from ts/pkjs/request.ts has its stamps taken back off. That text means the request is known never to have reached the provider, and every other error keeps the stamp. A request that throws answers NETWORK_ERROR, and so does a pluginRequest fetch the Pebble app refuses for a site the wearer has not allowed. A body pluginRequest cannot read after the host answered keeps its stamp, since the provider counted the call. It gives a non-2xx's status with no body, and FETCH_FAILED after a 2xx. With no key, or no place to ask, nothing is sent and the hook hears nothing. A hook or a returned function that throws is logged and passed over, so the run still finishes.

The Days the Pebble App Needs. The Pebble app builds the watch's own Weather app from an instance only when it holds today's and tomorrow's high, low, condition code, sunrise, and sunset. locationInstance answers null for a reading without two days from the place's today, a reading whose Open-Meteo half failed included. Leave that place out of the answer, so the Pebble app fills it from its own backend, or serve a failover reading for it. Through a polar night or a midnight sun the sunrise and sunset are gaps, so the instance goes out for faces and the Pebble app takes that place from its backend, as it would for the built-in.

Timeline Pins and Actions

Since Pebble app 1.18.0 a plugin app can hand pins to the Pebble app with Pebble.insertTimelinePin(pin) and take them off with Pebble.deleteTimelinePin(id), as PebbleKit JS does, and show a notification straight away with Pebble.showNotification({ layout, actions }). ts/plugin-app/timeline.ts types a pin from the pin guide as TimelinePin, with its layout, reminders, actions, and createNotification and updateNotification, and a notification as PluginNotification.

What a Pin Call Says. The Pebble app answers a pin call with nothing and never rejects. It drops a pin the plugin has no Timeline grant for, a pin that does not parse, and a delete of an id it does not know, all without a word. insertPin(pebble, pin) and deletePin(pebble, id) call the two safely and resolve to { ok: true } when the call was handed over, which does not mean the pin is on the watch. A call throws only when the pin cannot be turned into JSON. That, and a rejection should a later Pebble app reject, resolve to { ok: false, error } with the reason as failureReason words it, so a bad pin never ends the run. A Pebble app from before 1.18.0 has no pin calls, and both answer TIMELINE_UNAVAILABLE. A plugin that has to know its pins can show checks Pebble.permissions.query('Timeline') first, where the runtime has it.

Before the Answer. The Pebble app ends a plugin's run as soon as its request is answered, so a pin call made after answering may never run. Make every pin call, and wait for insertPin and deletePin, before answering.

The Rules a Pin Keeps. A pin's id is up to 64 characters and only has to be unique within the app, and inserting an id already there changes that pin. A pin needs Timeline, and its notifications need ShowNotifications too. The createNotification shows when a pin is first inserted, and the updateNotification when a later insert changes it. A pin has up to 3 reminders, and its body holds up to 512 characters. The guide holds a pin's time, and the times of its reminders and notifications, to no more than 2 days in the past and a year ahead. It states that for the timeline web API, so keep a plugin's pins inside it too.

A Deleted Id. The pin guide says a deleted pin's id cannot be used again, but writes that for the web API, and the local pins guide does not say whether a deleted local pin's id can be inserted again. Give a pin that comes back after a delete an id of its own, such as one with the event's start in it, rather than counting on either.

Actions on a Pin. A pluginAction on a pin or a notification, { title, type: 'pluginAction', action, args, inputArg?, replies? }, runs the plugin's own action handler with that action and args. The watch shows the handler's text, or Done, or Failed on an error. With inputArg the wearer replies by voice, emoji, or one of replies, and the reply arrives in args under that name. An app that invokes the actions of a plugin holding Internet needs InvokeAction naming that plugin, since the arguments can leave the phone.

Routing Actions. handleActions(actions) in ts/plugin-app/actions.ts registers the action handler and sends each request to the function named by its action. A function gets the request's args, or none when they are missing or a list, and answers with { text?, semanticResult?, refreshed? }, or nothing for Done. The answer is built field by field, keeping text and semanticResult only as text and only the text entries of refreshed, since the Pebble app turns down an answer with a field of the wrong type as UNKNOWN. A request naming an action the plugin does not have answers INVALID_REQUEST. A function that throws or rejects answers its error's code where it names one, such as AUTH_REQUIRED, or UNKNOWN, with its message. answerAction(actions, request, respond) is the same routing for a plugin that registers its own handler. The Pebble app takes the first answer, ignores any after it, and waits 20 seconds for one.

Specs. fakePluginPebble(options) in ts/testing/plugin-pebble.ts stands in for the plugin runtime's Pebble. It keeps the timeline by id, every pin call it took, and every notification. With { pins: 'dropped' } it takes each pin call and keeps nothing, as the Pebble app does with a pin it refuses, which is the failure to spec against. throw, reject, and missing check that a plugin holds up when a call fails outright or is not there. invoke(action, args) runs the action handler as the watch does and resolves to its first answer, however late, with a handler that throws or rejects first answered UNKNOWN.

Fetching from a Plugin App

A plugin app's runtime has no XMLHttpRequest and no timers, so the face's request in ts/pkjs/request.ts cannot run there. pluginRequest in ts/plugin-app/request.ts is the same call on the runtime's fetch, so the framework's weather and stock providers take it unchanged. It reports a non-2xx answer as http <status> with its body, so a 429 still reads as a rate limit, and gives a fetch up after 8 seconds with AbortSignal.timeout where the runtime has it. The Pebble app's fetch rejects every failure as a TypeError named only by its message, so pluginRequest reads the message as well. A fetch timeout: or fetch abort: answers timeout. A plain fetch failed: comes both from a request that never left and from a body the Pebble app could not read after the provider answered, so it answers FETCH_FAILED and keeps its stamp. Counting a call that never left costs a call of room, where missing one the provider counted can run a plan past its limit. fetchText is the same fetch for a whole document, such as an iCal feed. It throws HTTP <status> for an answer that is not 2xx. fetchFailure(error) sorts what it throws into one of FETCH_FAILURE_KINDS, codes a plugin app can keep and show on its settings page: HTTP with the answer's status, TIMEOUT for a fetch given up or aborted, NOT_ALLOWED for a host the wearer has not allowed, and FAILED for anything else. It sorts the error text pluginRequest answers too, http <status> in either case, timeout, and NETWORK_ERROR, which reads as NOT_ALLOWED for pluginRequest alone.

fetchQuotes(symbols, opts, request) in ts/stock/quotes.ts fetches a quote for each ticker from one provider and answers them in order, with a ticker whose fetch or provider throws answered as ERR. A failed quote carries no ticker, so read the answers by their order. Every ticker starts at once, and the runtime has no timers to space them, so under Alpha Vantage's free key ask for one ticker a run and serve the quotes held for the rest. Without AbortSignal.timeout a fetch that never answers holds the round until the Pebble app ends the run. roundStamps(results, nowMs) is the rule the stock feature uses for which rounds count against a provider's quota, and roundWait, rateLimitWait, and shouldThrottleStockFetch in ts/stock/schedule.ts are its waits and floors, so a plugin keeps a metered plan to the same count a face does. allowance in ts/stock/ledger.ts says how many calls fit inside a free plan, from the time each call went out, and keepSent, loadLedger, and saveLedger keep those times, per provider and per key by its keyPrint. keyPrint is fingerprint in ts/pkjs/fingerprint.ts, which a plugin app can use for its own keys and links, such as a feed's, to notice one changed without keeping it. Its output stays the same from release to release, since saved ledgers are keyed by it. COUNTED names the providers it counts, and STOCK_QUOTA_PLANS holds their plans. Stamp each call and save the stamps as it goes out, since the Pebble app can end a run partway through. A plugin and a face on the same key each keep their own stamps, so together they spend the key twice. parseSymbols(raw, max) in ts/stock/symbols.ts parses the wearer's ticker list with a cap of the caller's choosing.

Counting a Provider's Calls

ts/quota/ledger.ts is the ledger the stock feature counts with, for any metered provider. A QuotaPlan lists the provider's limits, each a number of calls in a minute, hour, day, or month window. A limit that follows: 'clock' starts again on the UTC minute, hour, midnight, or the 1st, and one that follows 'rolling' counts back from now, with a rolling month as the last 31 days. routineMax holds back the last few calls of a limit for the wearer's own asks, and keyed: false marks a keyless provider.

allowance(plan, stamps, ask, nowMs) says how many calls fit now and when the rest would. ask carries the number of calls, the weight of each for a provider that bills a big request as several calls, force for the wearer's own ask, and paid for a paid plan, which counts nothing. A weight is 1 or more, so one under 1 counts as 1, and an ask whose weight is not a number above 0 gets no room. windowOpensAt(limit, nowMs) says when a limit that is full now opens again, for a provider that answers RATE LIMIT on its own: the next UTC minute, hour, midnight, or 1st with the same margin allowance waits, or a rolling window's length from now. A fetchReading status of RATE LIMIT carries limit when the provider names the limit it hit, as WeatherAPI.com's quota code 2007 gives month, and a bare 429 names none. planFor(plans, id) looks a plan up by provider id, finding nothing for an id such as constructor.

addStamp stamps each call with its weight as it goes out, a weight that is not a number above 0 as 1, since a call sent anyway still spent it. takeBack removes the stamp of a call known never to have left, one that answers NETWORK_ERROR, matched on its time and its weight. saveStamps and loadStamps keep the stamps under a localStorage key the plugin names, per provider and per key fingerprint, and ledgerPrint(plan, key) gives the fingerprint, which is the same for every key on a keyless provider. A call of weight 1 is saved as its time and a heavier one as a time and weight pair. keepStamps lets go of what the plan's windows no longer see, and merges each hour that ended a day ago into one stamp, so a month window keeps a stamp an hour for the month plus one a call for the last day. loadStamps leaves out a saved weight above the plan's largest limit, and readStamps reads the stamps as they were saved, for a caller with its own rule for what to keep.