How rycursiv/hammerspoon-promise works
Project type and purpose
• Type: A standalone Lua module providing Promise/A+-style asynchronous programming primitives for Hammerspoon.
• Purpose: Offer Promise, async/await, fetch helpers (Promise.fetch, Promise.fetchImg), plus combinators (all, race, etc.) on top of Hammerspoon’s event loop and HTTP/image APIs.
File structure
• Single top-level file promise.lua containing the entire implementation.
• No subdirectories—this is a self-contained library.
• README outlines the public API and usage patterns.
README for insights
• Public constructors: Promise(executor) / Promise.new(executor).
• Static helpers: resolve, reject, all, race, sleep, fetch, fetchImg, async, await, etc.
• Instance methods: :next(), :catch(), :finally().
• Under the hood it schedules resolution/rejection via Hammerspoon’s event loop and wraps hs.http.doAsyncRequest and hs.image.imageFromURL.
Main components
a. User Script (Client)
– Invokes Promise.new, Promise.async, or any static helper.
– Chains .next(), .catch(), .finally().
b. Promise Core (Library)
– Executor function + internal state machine (pending → fulfilled/rejected).
– Callback queues for onFulfilled, onRejected, onFinally.
– Static combinators (all, race, allSettled, any).
– Sugar methods: sleep, fetch, fetchImg, async, await.
c. Hammerspoon Runtime
– Event loop: delivers callbacks back to the Lua VM.
– hs.http.doAsyncRequest: underlying HTTP.
– hs.image.imageFromURL: underlying image fetch.
d. External Services (optional)
– Remote HTTP endpoints invoked by Promise.fetch.
– Image servers used by Promise.fetchImg.
Relationships and interactions
• User → Promise Core: calls constructors, static methods, instance methods.
• Promise Core → Hammerspoon APIs:
– fetch() → hs.http.doAsyncRequest → onResponse callback → resolve/reject promise.
– fetchImg() → hs.image.imageFromURL → resolve with hs.image object.
• Promise Core → internal scheduler → Hammerspoon event loop → deferred invocation of handlers.
• Promise Core combinators (e.g. Promise.all) orchestrate multiple inner promises.
Architectural patterns and design principles
• State machine pattern: pending/fulfilled/rejected.
• Chainable interface: each .next() returns a new Promise.
• Functional combinators: all, race, any, allSettled.
• Async/await sugar: Promise.async wraps a function to allow Promise.await.
Detailed elements
• “Scheduler / Event Loop” connector illustrating how callbacks are deferred.
• “Async/Await Sugar” showing Promise.async(fn) and Promise.await(value).
• Life cycle: User calls Promise.async(fn)() → inside fn calls await(p) → the runtime suspends, schedules, resumes.