fostrom 0.0.12 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 HeadOn Labs LLP
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # Fostrom Device SDK
2
+
3
+ [Fostrom](https://fostrom.io) is an IoT Cloud Platform built for developers. Monitor and control your fleet of devices, from microcontrollers to industrial IoT. Designed to be simple, secure, and fast. Experience first-class tooling with Device SDKs, type-safe schemas, programmable actions, and more.
4
+
5
+ The Fostrom Device SDK for JavaScript works in Node.js and Bun, on Linux and macOS, and helps you quickly integrate, start monitoring, and controlling your IoT devices in just a few lines of code.
6
+
7
+ ## Example
8
+
9
+ ```js
10
+ import Fostrom from 'fostrom';
11
+
12
+ const fostrom = new Fostrom({
13
+ fleet_id: "<fleet-id>",
14
+ device_id: "<device-id>",
15
+ device_secret: "<device-secret>",
16
+ })
17
+
18
+ // Setup the on_mail handler, to process incoming mail.
19
+ fostrom.onMail = async (mail) => {
20
+ const {id, name, payload, mailbox_size} = mail
21
+ console.debug(`Received Mail (${mailbox_size}): ${name} ${id}`)
22
+
23
+ // You need to call `mail.ack()` to acknowledge the mail.
24
+ // Other options are: `mail.reject()` and `mail.requeue()`
25
+ // Note that if your function throws an error, the SDK will auto-reject the mail.
26
+ await mail.ack()
27
+ }
28
+
29
+ async function main() {
30
+ await fostrom.start()
31
+
32
+ // Send a message to Fostrom (payload can be null if schema has no payload)
33
+ await fostrom.sendMsg("<packet-schema-name>", { /* ...payload */ })
34
+
35
+ // Send a datapoint to Fostrom
36
+ await fostrom.sendDatapoint("<packet-schema-name>", { /* ...payload */ })
37
+ }
38
+
39
+ main()
40
+ ```
41
+
42
+ > Requires Node.js 22.12+ or Bun 1.1+
43
+
44
+ You can load the SDK via either syntax:
45
+
46
+ ```js
47
+ import Fostrom from 'fostrom'
48
+ ```
49
+
50
+ ```js
51
+ const { default: Fostrom } = require('fostrom')
52
+ ```
53
+
54
+ ## A Note on BigInts
55
+
56
+ Fostrom's Packet Schemas support defining `u64` and `i64` integers. However, JavaScript's `Number` type is limited to `2^53 - 1`. To rectify this issue, we use the `bigint` type and handle JSON encoding and decoding automatically.
57
+
58
+ Note that there's a caveat here. When Fostrom delivers a message to the SDK containing a `u64` or `i64` number, it will convert to the `Number` type if it is smaller than `2^53 - 1`, and convert to `bigint` if it is larger. This is because the SDK does not know if the field is a `u64` or `i64` type when converting. So for those fields you will need to check whether the type is `bigint` or not.
59
+
60
+ ## A Note on the Device Agent
61
+
62
+ The Fostrom Device SDK downloads and runs the Fostrom Device Agent in the background. The Agent is downloaded when the package is installed through `npm`. The Device Agent starts when `fostrom.start()` is called and handles communication with the Fostrom platform.
63
+
64
+ By default, the agent remains running in the background for fast reconnections. The SDK also installs a process exit handler; `fostrom.shutdown()` is called automatically on process exit, and if `stopAgentOnExit` is set to true in the config, the agent is stopped as well.
65
+
66
+ ## Logging
67
+
68
+ By default, the SDK logs connection and handler messages to the console. Set
69
+ `log: false` in the constructor config to silence SDK logs. Levels used:
70
+
71
+ - `console.info` for successful connection events
72
+ - `console.warn` for reconnection attempts
73
+ - `console.error` for unauthorized/critical errors
package/dl-agent.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  #
5
5
  # Usage: ./dl-agent.sh <directory>
6
6
 
7
- VERSION="latest"
7
+ VERSION="v0.0.13"
8
8
 
9
9
  # CDN URLs in order of preference
10
10
  CDN_PRIMARY="https://cdn.fostrom.dev/fostrom-device-agent/$VERSION"
@@ -138,7 +138,11 @@ main() {
138
138
  ;;
139
139
  Darwin*)
140
140
  OS="apple"
141
- ARCH="universal"
141
+ case "$ARCH" in
142
+ x86_64|amd64) ARCH="amd64" ;;
143
+ aarch64|arm64) ARCH="arm64" ;;
144
+ *) die "Unsupported architecture: $ARCH" ;;
145
+ esac
142
146
  ;;
143
147
  *) die "Unsupported OS: $OS" ;;
144
148
  esac
package/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { execSync } from "child_process"
2
2
  import { fileURLToPath } from "url"
3
3
  import path from "path"
4
+ import http from "node:http"
5
+ import { stringifyJSON, parseJSON } from "./json.js"
4
6
 
5
7
  function agent_path() {
6
8
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -9,10 +11,8 @@ function agent_path() {
9
11
 
10
12
  class FostromError extends Error {
11
13
  constructor(atom, msg) {
12
- const formattedMessage = `\x1b[31m\x1b[1mFostrom Error\x1b[0m \x1b[34m[${atom}]\x1b[0m ${msg}`
13
- super(formattedMessage)
14
- this.name = ""
15
- this.stack = null
14
+ super(`${atom}: ${msg}`)
15
+ this.error = atom
16
16
  }
17
17
  }
18
18
 
@@ -39,28 +39,39 @@ export class Mail {
39
39
  export default class Fostrom {
40
40
  #log = true
41
41
  #creds = {}
42
+ #sseBuffer = ""
43
+ #sseReq = null
44
+ #reconnectTimer = null
45
+ #stopped = true
46
+ #installedExitHandler = false
47
+ #stopAgentOnExit = false
48
+ #runtimeEnv = null
49
+
50
+ static #SOCK = "/tmp/fostrom/agent.sock"
42
51
 
43
52
  onMail = async mail => {
44
- console.log(`[Fostrom] Received Mail (Mailbox Size: ${mail.mailbox_size}): ${mail.name} -> ID ${mail.id}`)
45
- console.warn(" Auto-Acknowledging Mail. Define Mail Handler to handle incoming mail.\n `fostrom.on_mail = async (mail) => { ...; await mail.ack(); }`\n")
53
+ if (this.#log) {
54
+ console.warn(`[Fostrom] Received Mail (Mailbox Size: ${mail.mailbox_size}): ${mail.name} -> ID ${mail.id}`)
55
+ console.warn(" Auto-Acknowledging Mail. Define Mail Handler to handle incoming mail.\n `fostrom.on_mail = async (mail) => { ...; await mail.ack(); }`\n")
56
+ }
46
57
  await mail.ack()
47
58
  }
48
59
 
49
60
  connected = () => {
50
- if (this.#log) console.log("[Fostrom] Connected")
61
+ if (this.#log) console.info("[Fostrom] Connected")
51
62
  }
52
63
 
53
64
  unauthorized = (reason, after) => {
54
65
  if (this.#log) {
55
- const after_s = Math.floor(after / 1000);
56
- console.log(`[Fostrom] Unauthorized: ${reason}. Reconnecting in ${after_s} seconds...`)
66
+ const after_s = Math.floor((after || 0) / 1000);
67
+ console.error(`[Fostrom] Unauthorized: ${reason}. Reconnecting in ${after_s} seconds...`)
57
68
  }
58
69
  }
59
70
 
60
71
  reconnecting = (reason, after) => {
61
72
  if (this.#log) {
62
- const after_s = Math.floor(after / 1000);
63
- console.log(`[Fostrom] Failed to connect: ${reason}. Reconnecting in ${after_s} seconds...`)
73
+ const after_s = Math.floor((after || 0) / 1000);
74
+ console.warn(`[Fostrom] Failed to connect: ${reason}. Reconnecting in ${after_s} seconds...`)
64
75
  }
65
76
  }
66
77
 
@@ -72,77 +83,85 @@ export default class Fostrom {
72
83
  this.#creds.device_id = config.device_id
73
84
  this.#creds.device_secret = config.device_secret
74
85
  if (config.log == false) this.#log = false
86
+ this.#stopAgentOnExit = Boolean(config.stopAgentOnExit || false)
87
+ this.#runtimeEnv = config.env || config.runtimeEnv || process.env.NODE_ENV || null
88
+ }
89
+
90
+ #installExitHandler() {
91
+ if (this.#installedExitHandler) return
92
+ process.on('exit', () => {
93
+ try { this.shutdown() } catch { }
94
+ })
95
+ this.#installedExitHandler = true
75
96
  }
76
97
 
77
98
  #start_agent() {
78
99
  const { fleet_id, device_id, device_secret } = this.#creds
79
100
 
80
- let args = [
81
- "start",
82
- "--fleet-id", fleet_id,
83
- "--device-id", device_id,
84
- "--device-secret", device_secret
85
- ]
101
+ const env = {
102
+ ...process.env,
103
+ FOSTROM_FLEET_ID: fleet_id,
104
+ FOSTROM_DEVICE_ID: device_id,
105
+ FOSTROM_DEVICE_SECRET: device_secret,
106
+ }
107
+ if (this.#runtimeEnv && String(this.#runtimeEnv).trim() !== "") {
108
+ env["FOSTROM_RUNTIME_ENV"] = String(this.#runtimeEnv)
109
+ }
86
110
 
87
- if (process.env.FOSTROM_AGENT_MODE === 'dev') args.push("--dev")
111
+ const args = ["start"]
88
112
 
89
113
  try {
90
- const output = execSync(`${agent_path()} ${args.join(" ")}`, { encoding: "utf8" })
91
-
92
- if (output.trim() == "started") {
93
- return
94
- }
114
+ const output = execSync(`${agent_path()} ${args.join(" ")}`, { encoding: "utf8", env })
115
+ const out = output.trim()
116
+ if (out.startsWith("started:")) return
117
+ if (out.startsWith("already_started:")) return
118
+ return
95
119
  } catch (error) {
96
- let [err, msg] = error.stdout.trim().split(":", 2)
97
- throw new FostromError(err, msg)
120
+ const out = (error.stdout || "").toString().trim()
121
+ if (out) {
122
+ const [atom, rest] = out.split(":", 2)
123
+ throw new FostromError(atom || "failed", (rest || "Failed to start Device Agent").trim())
124
+ }
125
+ throw new FostromError("failed", "Failed to start Device Agent")
98
126
  }
99
127
  }
100
128
 
101
- async #req(path = "/", method = "GET", payload = null, additional_options = {}) {
102
- if (method != "GET" && method != "PUT" && method != "POST" && method != "DELETE") {
129
+ async #req(path = "/", method = "GET", payload = null) {
130
+ if (!["GET", "PUT", "POST", "DELETE", "HEAD"].includes(method)) {
103
131
  throw new Error(`Unsupported ${method} Request for path ${path}`)
104
132
  }
105
133
 
106
- const headers = new Headers()
107
- headers.set("Content-Type", "application/json")
108
- headers.set("Accept", "application/json")
109
-
110
- const base_options = {
111
- method,
112
- headers,
113
- }
114
-
115
- if ((method == "POST" || method == "PUT") && payload) {
116
- base_options.body = JSON.stringify(payload)
134
+ const { fleet_id, device_id } = this.#creds
135
+ const headers = {
136
+ "X-Fleet-ID": fleet_id,
137
+ "X-Device-ID": device_id,
117
138
  }
118
139
 
119
- const options = {
120
- ...base_options,
121
- ...additional_options
140
+ let bodyString = null
141
+ if (method === "POST" || method === "PUT") {
142
+ headers["Content-Type"] = "application/json; charset=utf-8"
143
+ headers["Accept"] = "application/json"
144
+ if (payload === undefined || payload === null) {
145
+ bodyString = "null"
146
+ } else {
147
+ bodyString = stringifyJSON(payload)
148
+ }
149
+ headers["Content-Length"] = Buffer.byteLength(bodyString, 'utf8')
150
+ } else {
151
+ headers["Accept"] = "application/json"
122
152
  }
123
153
 
124
- let resp
125
- let body
154
+ const res = await Fostrom.#unix_request({ path, method, headers, body: bodyString })
126
155
 
127
- try {
128
- resp = await fetch(`http://localhost:8585${path}`, options)
129
- } catch (e) {
130
- throw new FostromError("req_failed", "Communicating with the device agent is failing.")
131
- }
132
-
133
- try {
134
- body = await resp.json()
135
- }
136
- catch (e) {
137
- console.error(e)
138
- throw new FostromError("req_failed", "Communicating with the device agent is failing.")
156
+ if (res.statusCode < 200 || res.statusCode >= 300) {
157
+ if (res.bodyJson && res.bodyJson.error) {
158
+ const msg = res.bodyJson.msg || "Request failed"
159
+ throw new FostromError(res.bodyJson.error, msg)
160
+ }
161
+ throw new FostromError("request_failed", "Communicating with the Device Agent failed")
139
162
  }
140
163
 
141
- if (body.error && body.msg) {
142
- throw new FostromError(body.error, body.msg)
143
- } else {
144
- return body
145
- }
164
+ return res
146
165
  }
147
166
 
148
167
  static stopAgent() {
@@ -153,53 +172,68 @@ export default class Fostrom {
153
172
  }
154
173
  }
155
174
 
156
- async connect() {
175
+ async start() {
176
+ if (!this.#stopped) return
177
+ this.#installExitHandler()
157
178
  this.#start_agent()
158
- const resp = await this.#req()
159
- const status = resp.connect_status
179
+ this.#stopped = false
180
+ this.#open_event_stream()
181
+ }
160
182
 
161
- if (!status.connected) {
162
- console.error(new FostromError(status.error, status.msg))
163
- } else {
164
- this.#open_event_stream()
165
- return true
166
- }
183
+ async shutdown(stopAgent = null) {
184
+ this.#stopped = true
185
+ try {
186
+ if (this.#reconnectTimer) {
187
+ clearTimeout(this.#reconnectTimer)
188
+ this.#reconnectTimer = null
189
+ }
190
+ if (this.#sseReq && typeof this.#sseReq.destroy === 'function') {
191
+ this.#sseReq.destroy()
192
+ }
193
+ } catch { }
194
+ this.#sseReq = null
195
+ const doStop = (stopAgent === null) ? this.#stopAgentOnExit : Boolean(stopAgent)
196
+ if (doStop) Fostrom.stopAgent()
167
197
  }
168
198
 
169
199
  async sendDatapoint(name, payload) {
170
- return await this.#req(`/pulse/datapoint/${name}`, "POST", payload)
200
+ Fostrom.#validate_pulse_name(name)
201
+ const res = await this.#req(`/pulse/datapoint/${name}`, "POST", payload)
202
+ return
171
203
  }
172
204
 
173
205
  async sendMsg(name, payload) {
174
- return await this.#req(`/pulse/msg/${name}`, "POST", payload)
206
+ Fostrom.#validate_pulse_name(name)
207
+ const res = await this.#req(`/pulse/msg/${name}`, "POST", payload)
208
+ return
175
209
  }
176
210
 
177
211
  async mailboxStatus() {
178
- const resp = await this.#req(`/mailbox/status`)
179
-
180
- if (resp.mailbox_empty == true) {
181
- return {
182
- mailbox_size: 0,
183
- next_mail_id: null,
184
- next_mail_name: null
185
- }
186
- } else {
187
- return {
188
- mailbox_size: resp.mailbox_size,
189
- next_mail_id: resp.pulse_id,
190
- next_mail_name: resp.name,
191
- }
212
+ const res = await this.#req(`/mailbox/next`, "HEAD")
213
+ const h = res.headers
214
+ const empty = Fostrom.#parse_bool(h["x-mailbox-empty"]) === true
215
+ if (empty) {
216
+ return { mailbox_size: 0, next_mail_id: null, next_mail_name: null }
217
+ }
218
+ return {
219
+ mailbox_size: Number(h["x-mailbox-size"]) || 0,
220
+ next_mail_id: Number(h["x-mail-id"]) || null,
221
+ next_mail_name: h["x-mail-name"] || null,
192
222
  }
193
223
  }
194
224
 
195
225
  async nextMail() {
196
- const resp = await this.#req(`/mailbox/next`)
197
-
198
- if (resp.mailbox_empty == true) {
199
- return null
200
- }
201
-
202
- return new Mail(this, resp.pulse_id, resp.name, resp.payload, resp.mailbox_size)
226
+ const res = await this.#req(`/mailbox/next`, "GET")
227
+ const h = res.headers
228
+ const empty = Fostrom.#parse_bool(h["x-mailbox-empty"]) === true
229
+ if (empty) return null
230
+
231
+ const mailbox_size = Number(h["x-mailbox-size"]) || 0
232
+ const id = Number(h["x-mail-id"]) || null
233
+ const name = h["x-mail-name"] || null
234
+ const hasPayload = Fostrom.#parse_bool(h["x-mail-has-payload"]) === true
235
+ const payload = hasPayload ? (res.bodyJson ?? null) : null
236
+ return new Mail(this, id, name, payload, mailbox_size)
203
237
  }
204
238
 
205
239
  async __mail_op(op, mail_id) {
@@ -207,72 +241,185 @@ export default class Fostrom {
207
241
  throw new Error("Invalid Mailbox Operation")
208
242
  }
209
243
 
210
- return await this.#req(`/mailbox/${op}/${mail_id}`, "PUT")
244
+ const res = await this.#req(`/mailbox/${op}/${mail_id}`, "PUT")
245
+ const more = Fostrom.#parse_bool(res.headers["x-mail-available"]) === true
246
+ if (more) {
247
+ const mail = await this.nextMail()
248
+ if (mail) await this.#deliverMail(mail)
249
+ }
250
+ return true
211
251
  }
212
252
 
213
253
  async #event_handler(event_object) {
214
- const { event, _timestamp } = event_object
254
+ const { event } = event_object
215
255
  const data = event_object.data
216
256
 
217
257
  switch (event) {
218
- case 'connected': this.connected(); break;
219
- case 'unauthorized': this.unauthorized(data.reason, data.reconnecting_in); break;
220
- case 'connect_failed': this.reconnecting(data.reason, data.reconnecting_in); break;
221
- case 'next_mail': this.#dispatch_next_mail(data); break;
222
- default: null
258
+ case 'connected':
259
+ this.connected()
260
+ break
261
+ case 'disconnected': {
262
+ if (data && typeof data.error === 'string') {
263
+ const err = data.error
264
+ const after = Number(data.reconnecting_in_ms || 0)
265
+ const reason = (typeof err === 'string') ? err.split(':', 2)[0].trim() : ''
266
+ if (reason === "unauthorized") this.unauthorized(err, after)
267
+ else this.reconnecting(err, after)
268
+ }
269
+ break
270
+ }
271
+ case 'new_mail': {
272
+ const mail = await this.nextMail()
273
+ if (mail) await this.#deliverMail(mail)
274
+ break
275
+ }
276
+ default:
277
+ break
223
278
  }
224
279
  }
225
280
 
226
- async #dispatch_next_mail(data) {
227
- const mail = new Mail(this, data.pulse_id, data.name, data.payload, data.mailbox_size)
228
- this.onMail(mail)
229
- }
230
-
231
281
  async #open_event_stream() {
232
- const td = new TextDecoder()
282
+ if (this.#stopped) return
283
+ if (this.#sseReq) return
284
+ const { fleet_id, device_id } = this.#creds
285
+ const options = {
286
+ socketPath: Fostrom.#SOCK,
287
+ path: "/events",
288
+ method: "GET",
289
+ headers: {
290
+ "Accept": "text/event-stream",
291
+ "X-Fleet-ID": fleet_id,
292
+ "X-Device-ID": device_id,
293
+ "Connection": "keep-alive",
294
+ }
295
+ }
233
296
 
234
- const resp = await fetch(`http://localhost:8585/events`, {
235
- headers: { 'Accept': 'text/event-stream' }
297
+ const req = http.request(options, (res) => {
298
+ res.setEncoding('utf8')
299
+ res.on('data', (chunk) => {
300
+ this.#sseBuffer = Fostrom.#parse_events(this.#sseBuffer, chunk, this.#event_handler.bind(this))
301
+ })
302
+ res.on('error', () => {
303
+ this.#sseReq = null
304
+ if (!this.#stopped) {
305
+ this.#reconnectTimer = setTimeout(() => this.#open_event_stream(), 500)
306
+ }
307
+ })
308
+ res.on('aborted', () => {
309
+ this.#sseReq = null
310
+ if (!this.#stopped) {
311
+ this.#reconnectTimer = setTimeout(() => this.#open_event_stream(), 500)
312
+ }
313
+ })
314
+ res.on('end', () => {
315
+ this.#sseReq = null
316
+ if (!this.#stopped) {
317
+ this.#reconnectTimer = setTimeout(() => this.#open_event_stream(), 250)
318
+ }
319
+ })
236
320
  })
237
321
 
238
- const reader = resp.body.getReader()
239
- let buffer = ''
322
+ req.on('error', (_err) => {
323
+ this.#sseReq = null
324
+ if (!this.#stopped) {
325
+ this.#reconnectTimer = setTimeout(() => this.#open_event_stream(), 500)
326
+ }
327
+ })
240
328
 
241
- while (true) {
242
- const { done, value } = await reader.read()
243
- if (done) { this.connect() }
244
- const decoded = td.decode(value)
245
- parse_events(buffer, decoded, this.#event_handler.bind(this))
246
- }
329
+ req.end()
330
+ this.#sseReq = req
331
+ }
332
+
333
+ // --- Static helpers ---
334
+ static #parse_bool(v) {
335
+ if (typeof v !== 'string') return false
336
+ const s = v.toLowerCase()
337
+ return s === 'true' || s === '1' || s === 'yes'
247
338
  }
248
- }
249
339
 
250
- function parse_events(buffer, chunk, event_handler) {
251
- buffer += chunk
252
- const lines = buffer.split('\n')
340
+ static #validate_pulse_name(name) {
341
+ if (typeof name !== 'string') name = String(name)
342
+ if (name.length === 0 || name.length > 255) {
343
+ throw new FostromError('invalid_name', 'Pulse name must be 1..255 characters')
344
+ }
345
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) {
346
+ throw new FostromError('invalid_name', 'Pulse name may contain only A-Za-z0-9_-')
347
+ }
348
+ }
253
349
 
254
- // Keep the last incomplete line in buffer
255
- buffer = lines.pop() || ''
350
+ static async #unix_request({ path, method, headers = {}, body = null }) {
351
+ return new Promise((resolve, reject) => {
352
+ const opts = {
353
+ socketPath: Fostrom.#SOCK,
354
+ path,
355
+ method,
356
+ headers,
357
+ }
256
358
 
257
- let event = {}
359
+ const req = http.request(opts, (res) => {
360
+ const chunks = []
361
+ res.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
362
+ res.on('end', () => {
363
+ const bodyBuf = Buffer.concat(chunks)
364
+ const bodyText = bodyBuf.toString('utf8')
365
+ const ct = res.headers['content-type'] || ''
366
+ let bodyJson = null
367
+ if (ct.toLowerCase().includes('application/json') && bodyText.length > 0) {
368
+ try { bodyJson = parseJSON(bodyText) } catch { bodyJson = null }
369
+ }
370
+ resolve({
371
+ statusCode: res.statusCode || 0,
372
+ headers: res.headers || {},
373
+ bodyText,
374
+ bodyJson,
375
+ })
376
+ })
377
+ })
378
+
379
+ req.on('error', (err) => {
380
+ reject(new FostromError('req_failed', `Communicating with the Device Agent failed: ${err.message}`))
381
+ })
382
+
383
+ if (body !== null && body !== undefined && method !== 'HEAD') {
384
+ req.write(body)
385
+ }
386
+ req.end()
387
+ })
388
+ }
258
389
 
259
- for (const line of lines) {
260
- // Empty line indicates end of event
261
- if (line === '') {
262
- if (event.data && event.data != '') {
263
- event.data = JSON.parse(event.data)
390
+ static #parse_events(buffer, chunk, event_handler) {
391
+ buffer += chunk
392
+ const lines = buffer.split('\n')
393
+ buffer = lines.pop() || ''
394
+
395
+ let event = {}
396
+ for (const raw of lines) {
397
+ const line = raw.replace(/\r$/, '')
398
+ if (line === '') {
399
+ if (event.data && event.data !== '') {
400
+ try { event.data = parseJSON(event.data) } catch { /* ignore */ }
401
+ }
402
+ if (event.event) event_handler(event)
403
+ event = {}
404
+ } else if (line.startsWith('data: ')) {
405
+ event.data = (event.data || '') + line.slice(6)
406
+ } else if (line.startsWith('event: ')) {
407
+ event.event = line.slice(7)
408
+ } else if (line.startsWith('id: ')) {
409
+ const ts = parseInt(line.slice(4))
410
+ if (!Number.isNaN(ts)) event.timestamp = new Date(ts)
264
411
  }
412
+ }
265
413
 
266
- event_handler(event)
267
- event = {}
268
- } else if (line.startsWith('data: ')) {
269
- event.data = (event.data || '') + line.slice(6)
270
- } else if (line.startsWith('event: ')) {
271
- event.event = line.slice(7)
272
- } else if (line.startsWith('id: ')) {
273
- event.timestamp = new Date(parseInt(line.slice(4)))
274
- } else if (line.startsWith('retry: ')) {
275
- event.retry = parseInt(line.slice(7))
414
+ return buffer
415
+ }
416
+
417
+ async #deliverMail(mail) {
418
+ try {
419
+ await this.onMail(mail)
420
+ } catch (e) {
421
+ if (this.#log) console.error(`[Fostrom] onMail handler threw; auto-rejecting mail ${mail.id} (${mail.name})`, e)
422
+ try { await mail.reject() } catch { }
276
423
  }
277
424
  }
278
425
  }
package/json.js ADDED
@@ -0,0 +1,31 @@
1
+ // JSON functions to correctly handle BigInts
2
+
3
+ function stringifyJSON(value) {
4
+ if (typeof JSON.rawJSON !== 'function') {
5
+ throw new Error('JSON.rawJSON not available; requires Node.js 22+/Bun 1.1+')
6
+ }
7
+ return JSON.stringify(value, (_key, v) => {
8
+ if (typeof v === 'bigint') {
9
+ return JSON.rawJSON(v.toString())
10
+ }
11
+ return v
12
+ })
13
+ }
14
+
15
+ function parseJSON(text) {
16
+ if (typeof JSON.rawJSON !== 'function') {
17
+ throw new Error('JSON.rawJSON not available; requires Node.js 22+/Bun 1.1+')
18
+ }
19
+ return JSON.parse(text, (_key, v, ctx) => {
20
+ if (typeof v === 'number' && Number.isInteger(v) && !Number.isSafeInteger(v) && ctx?.source) {
21
+ try {
22
+ return BigInt(ctx.source)
23
+ } catch {
24
+ return v
25
+ }
26
+ }
27
+ return v
28
+ })
29
+ }
30
+
31
+ export { stringifyJSON, parseJSON }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fostrom",
3
- "version": "0.0.12",
3
+ "version": "0.0.15",
4
4
  "description": "Fostrom's Official Device SDK for JS. Fostrom (https://fostrom.io) is an IoT Cloud Platform.",
5
5
  "keywords": [
6
6
  "fostrom",
@@ -18,17 +18,31 @@
18
18
  "raspberry"
19
19
  ],
20
20
  "homepage": "https://docs.fostrom.io/sdk/js",
21
- "license": "MIT",
21
+ "license": "Apache-2.0",
22
22
  "author": "Fostrom <support@fostrom.io> (https://fostrom.io)",
23
23
  "files": [
24
24
  "index.js",
25
+ "json.js",
25
26
  "dl-agent.sh",
26
- "readme.md"
27
+ "README.md",
28
+ "LICENSE"
27
29
  ],
28
30
  "main": "index.js",
29
31
  "type": "module",
32
+ "exports": {
33
+ ".": {
34
+ "module-sync": "./index.js",
35
+ "import": "./index.js",
36
+ "default": "./index.js"
37
+ },
38
+ "./package.json": "./package.json",
39
+ "./dl-agent.sh": "./dl-agent.sh"
40
+ },
30
41
  "scripts": {
31
42
  "postinstall": "sh dl-agent.sh .agent"
32
43
  },
44
+ "engines": {
45
+ "node": ">=22.12.0"
46
+ },
33
47
  "dependencies": {}
34
48
  }
package/readme.md DELETED
@@ -1,44 +0,0 @@
1
- # Fostrom Device SDK
2
-
3
- [Fostrom](https://fostrom.io) is an IoT Cloud Platform built for developers. Monitor and control your fleet of devices, from microcontrollers to industrial IoT. Designed to be simple, secure, and fast. Experience first-class tooling with Device SDKs, type-safe schemas, programmable actions, and more.
4
-
5
- The Fostrom Device SDK for JavaScript works in Node.js and Bun, on Linux and macOS, and helps you quickly integrate, start monitoring, and controlling your IoT devices in just a few lines of code.
6
-
7
- ## Example
8
-
9
- ```js
10
- import Fostrom from 'fostrom';
11
-
12
- const fostrom = new Fostrom({
13
- fleet_id: "<fleet-id>",
14
- device_id: "<device-id>",
15
- device_secret: "<device-secret>",
16
- })
17
-
18
- // Setup the on_mail handler, to process incoming mail.
19
- fostrom.onMail = async (mail) => {
20
- const {id, name, payload, mailbox_size} = mail
21
- console.debug(`Received Mail (${mailbox_size}): ${name} ${id}`)
22
- await mail.ack()
23
- }
24
-
25
- async function main() {
26
- await fostrom.connect()
27
-
28
- // To send a message to Fostrom
29
- await fostrom.sendMsg("<packet-schema-name>", { ...payload })
30
-
31
- // To send a datapoint to Fostrom
32
- await fostrom.sendDatapoint("<packet-schema-name>", { ...payload })
33
- }
34
-
35
- main()
36
- ```
37
-
38
- Please note, to use `import Fostrom from 'fostrom';` you'll need to set `"type": "module"` in `package.json`.
39
-
40
- ## A Note on the Device Agent
41
-
42
- The Fostrom Device SDK downloads and runs the Fostrom Device Agent in the background. The Agent is downloaded when the package is installed through `npm`. The Device Agent is started when `fostrom.connect()` is called, and it remains running in the background forever.
43
-
44
- We recommend you allow the Device Agent to run continously, even if your program has exited or crashed, so that when your program is automatically restarted by a process manager, the reconnection to Fostrom is nearly instant. However, if you wish to stop the Device Agent, you can call `Fostrom.stopAgent()` in your code before terminating your program.