@octane-xplat/background-tasks 0.0.0-nightly.g1b95ef7

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/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @octane-xplat/background-tasks
2
+
3
+ [Documentation](https://octane-xplat.goddardai.org/package-background-tasks).
4
+
5
+ [API reference](https://octane-xplat.goddardai.org/api-background-tasks).
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@octane-xplat/background-tasks",
3
+ "version": "0.0.0-nightly.g1b95ef7",
4
+ "description": "OS-scheduled periodic background work for Octane xplat — BGTaskScheduler and WorkManager",
5
+ "keywords": [
6
+ "android",
7
+ "cross-platform",
8
+ "nativescript",
9
+ "octane",
10
+ "xplat",
11
+ "background-tasks",
12
+ "background-fetch",
13
+ "workmanager"
14
+ ],
15
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/background-tasks",
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/octane-xplat/octane-xplat",
20
+ "directory": "packages/background-tasks"
21
+ },
22
+ "files": [
23
+ "src",
24
+ "platforms",
25
+ "types",
26
+ "!src/**/*.test.*",
27
+ "!src/**/*.spec.*"
28
+ ],
29
+ "type": "module",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./types/generated/index.d.ts",
33
+ "macos": "./src/index.macos.ts",
34
+ "web": "./src/index.web.ts",
35
+ "native": "./src/index.ts",
36
+ "default": "./src/index.ts"
37
+ },
38
+ "./*": {
39
+ "types": "./types/generated/*.d.ts",
40
+ "default": "./src/*"
41
+ },
42
+ "./*.ts": {
43
+ "types": "./types/generated/*.d.ts",
44
+ "default": "./src/*.ts"
45
+ }
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "test": "node --test tests/*.test.ts tests/*.test.mts",
52
+ "typegen": "tsrx-typegen --target octane",
53
+ "prepack": "bun run typegen && tsrx-typegen --pack-check",
54
+ "pack:check": "tsrx-typegen --pack-check",
55
+ "typecheck": "node ../../scripts/typecheck.ts"
56
+ },
57
+ "devDependencies": {
58
+ "@octane-xplat/nativescript-octane": "0.0.0-nightly.g1b95ef7",
59
+ "@nativescript/core": "9.1.3",
60
+ "@nativescript/types": "9.1.4",
61
+ "octane": "0.23.2",
62
+ "tsrx-typegen": "0.6.2",
63
+ "typescript": "7.1.0-dev.20261121.1",
64
+ "@tsrx/content-mapper": "0.1.2",
65
+ "typescript-classic": "npm:typescript@5.9.3"
66
+ },
67
+ "peerDependencies": {
68
+ "@octane-xplat/nativescript-octane": "0.0.0-nightly.g1b95ef7",
69
+ "@nativescript/core": ">=9.1.0 <10",
70
+ "octane": ">=0.6.3 <1"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "@octane-xplat/nativescript-octane": {
74
+ "optional": true
75
+ },
76
+ "@nativescript/core": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "nativescript": {
81
+ "platforms": {
82
+ "android": "9.1.0",
83
+ "ios": "9.1.0"
84
+ }
85
+ },
86
+ "dependencies": {
87
+ "@octane-xplat/platform": "0.0.0-nightly.g1b95ef7"
88
+ }
89
+ }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <!-- WorkManager registers its initializer via a library content provider;
3
+ no app manifest entries are required. -->
4
+ </manifest>
@@ -0,0 +1,3 @@
1
+ dependencies {
2
+ implementation "androidx.work:work-runtime:2.9.1"
3
+ }
@@ -0,0 +1,20 @@
1
+ package com.octanexplat.tasks;
2
+
3
+ import android.content.Context;
4
+ import androidx.work.*;
5
+ import java.util.concurrent.TimeUnit;
6
+
7
+ public class TaskScheduler {
8
+ public static void schedule(Context context, String name, long intervalSeconds) {
9
+ long interval = Math.max(intervalSeconds, 15 * 60); // WorkManager floor
10
+ PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(TaskWorker.class, interval, TimeUnit.SECONDS)
11
+ .addTag("xplat:" + name)
12
+ .build();
13
+ WorkManager.getInstance(context.getApplicationContext())
14
+ .enqueueUniquePeriodicWork("xplat:" + name, ExistingPeriodicWorkPolicy.UPDATE, request);
15
+ }
16
+
17
+ public static void cancel(Context context, String name) {
18
+ WorkManager.getInstance(context.getApplicationContext()).cancelUniqueWork("xplat:" + name);
19
+ }
20
+ }
@@ -0,0 +1,88 @@
1
+ package com.octanexplat.tasks;
2
+
3
+ import android.content.Context;
4
+ import androidx.work.*;
5
+ import com.tns.Runtime;
6
+ import java.util.concurrent.CountDownLatch;
7
+ import java.util.concurrent.TimeUnit;
8
+
9
+ public class TaskWorker extends Worker {
10
+ private static final long RESULT_TIMEOUT_MS = 25_000;
11
+
12
+ // Implemented by the JS module. Calls dispatched from Java run on the JS
13
+ // thread through the NativeScript proxy and block until it returns.
14
+ public interface TaskRunner {
15
+ void run(String name, TaskOutcome outcome);
16
+ }
17
+
18
+ // The JS side reports the executor's settled result through onResult;
19
+ // the first report wins and releases the waiting worker thread.
20
+ public static class TaskOutcome {
21
+ private final CountDownLatch done = new CountDownLatch(1);
22
+ private volatile String result = "failed";
23
+
24
+ public void onResult(String value) {
25
+ if (done.getCount() == 0) {
26
+ return;
27
+ }
28
+ result = value == null ? "failed" : value;
29
+ done.countDown();
30
+ }
31
+
32
+ String result() {
33
+ return result;
34
+ }
35
+
36
+ boolean await() throws InterruptedException {
37
+ return done.await(RESULT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
38
+ }
39
+ }
40
+
41
+ private static volatile TaskRunner runner;
42
+
43
+ // The JS module registers its runner at evaluation time — the supported
44
+ // Java→JS bridge needs a JS-implemented object, not a global function.
45
+ public static void setTaskRunner(TaskRunner taskRunner) {
46
+ runner = taskRunner;
47
+ }
48
+
49
+ public TaskWorker(Context context, WorkerParameters params) {
50
+ super(context, params);
51
+ }
52
+
53
+ @Override
54
+ public Result doWork() {
55
+ String name = getTags().stream()
56
+ .filter(t -> t.startsWith("xplat:"))
57
+ .map(t -> t.substring(6))
58
+ .findFirst()
59
+ .orElse(null);
60
+ if (name == null) {
61
+ return Result.failure();
62
+ }
63
+ if (Runtime.getCurrentRuntime() == null) {
64
+ // Cold start: the runtime isn't up — WorkManager retry re-runs us.
65
+ return Result.retry();
66
+ }
67
+ TaskRunner taskRunner = runner;
68
+ if (taskRunner == null) {
69
+ // Warm runtime whose module evaluation never registered a runner.
70
+ return Result.retry();
71
+ }
72
+ TaskOutcome outcome = new TaskOutcome();
73
+ try {
74
+ taskRunner.run(name, outcome);
75
+ } catch (Throwable t) {
76
+ return Result.retry();
77
+ }
78
+ try {
79
+ if (!outcome.await()) {
80
+ return Result.retry();
81
+ }
82
+ } catch (InterruptedException e) {
83
+ Thread.currentThread().interrupt();
84
+ return Result.retry();
85
+ }
86
+ return "success".equals(outcome.result()) ? Result.success() : Result.retry();
87
+ }
88
+ }
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>UIBackgroundModes</key>
6
+ <array>
7
+ <string>fetch</string>
8
+ <string>processing</string>
9
+ </array>
10
+ <!-- Apps must also add their task identifiers:
11
+ <key>BGTaskSchedulerPermittedIdentifiers</key>
12
+ <array><string>com.octanexplat.tasks.TASK_NAME</string></array> -->
13
+ </dict>
14
+ </plist>
@@ -0,0 +1,16 @@
1
+ // Unsupported leaf — platform-specific schedulers (NSBackgroundActivityScheduler
2
+ // on macOS) are follow-ups; the API surface stands.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () =>
6
+ Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
7
+
8
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
9
+ export const backgroundTasks: BackgroundTasks = {
10
+ supported: false,
11
+ defineTask: () => {},
12
+ register: unsupported,
13
+ unregister: unsupported,
14
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
+ isRegistered: async () => false,
16
+ }
@@ -0,0 +1,89 @@
1
+ // Background tasks — AppKit leaf over NSBackgroundActivityScheduler. The
2
+ // scheduler is deferrable maintenance work: `interval` is a request the OS
3
+ // may stretch, the app must be running (no launch-on-event), and a deferred
4
+ // fire surfaces TaskResult through the executor's completion.
5
+ import { NSBackgroundActivityScheduler } from '@octane-xplat/platform/macos'
6
+ import type { BackgroundTasks, TaskExecutor, TaskResult, TaskStatus } from './types'
7
+
8
+ // NSBackgroundActivityResult: 1 deferred, 2 finished.
9
+ const RESULT_FINISHED = 2
10
+ const RESULT_DEFERRED = 1
11
+
12
+ const executors = new Map<string, TaskExecutor>()
13
+ const schedulers = new Map<string, any>()
14
+
15
+ const schedulerClass = (): any => {
16
+ try {
17
+ return typeof NSBackgroundActivityScheduler?.alloc === 'function'
18
+ ? NSBackgroundActivityScheduler
19
+ : null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
25
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
26
+ export const backgroundTasks: BackgroundTasks = {
27
+ get supported() {
28
+ return schedulerClass() !== null
29
+ },
30
+
31
+ defineTask(name: string, executor: TaskExecutor): void {
32
+ executors.set(name, executor)
33
+ },
34
+
35
+ register: async (name: string, options?: { minimumInterval?: number }): Promise<void> => {
36
+ if (!executors.has(name)) {
37
+ throw new Error(`backgroundTasks.register: no task defined as '${name}'`)
38
+ }
39
+
40
+ const klass = schedulerClass()
41
+
42
+ if (!klass) {
43
+ throw new Error('backgroundTasks.register: NSBackgroundActivityScheduler is unavailable')
44
+ }
45
+
46
+ backgroundTasks.unregister(name).catch(() => {})
47
+
48
+ const scheduler = klass.alloc().initWithIdentifier(`xplat.background.${name}`)
49
+
50
+ scheduler.repeats = true
51
+ scheduler.interval = Math.max(options?.minimumInterval ?? 3600, 60)
52
+ scheduler.tolerance = scheduler.interval / 2
53
+ scheduler.qualityOfService = 0x09 // NSQualityOfServiceBackground
54
+ scheduler.scheduleWithBlock((completion: (result: number) => void) => {
55
+ const executor = executors.get(name)
56
+
57
+ if (scheduler.shouldDefer || !executor) {
58
+ completion(RESULT_DEFERRED)
59
+ return
60
+ }
61
+
62
+ Promise.resolve()
63
+ .then(() => executor({ name, expired: false }))
64
+ .then((result: TaskResult) =>
65
+ completion(result === 'success' ? RESULT_FINISHED : RESULT_DEFERRED),
66
+ )
67
+ .catch(() => completion(RESULT_DEFERRED))
68
+ })
69
+
70
+ schedulers.set(name, scheduler)
71
+ },
72
+
73
+ unregister: async (name: string): Promise<void> => {
74
+ const scheduler = schedulers.get(name)
75
+
76
+ if (scheduler) {
77
+ schedulers.delete(name)
78
+ try {
79
+ scheduler.invalidate()
80
+ } catch {
81
+ // Invalidating a released scheduler must not poison unregister.
82
+ }
83
+ }
84
+ },
85
+
86
+ getStatus: async (): Promise<TaskStatus> => (schedulerClass() ? 'available' : 'unavailable'),
87
+
88
+ isRegistered: async (name: string): Promise<boolean> => schedulers.has(name),
89
+ }
@@ -0,0 +1,260 @@
1
+ // Background tasks — native leaf, custom bridge (no NS plugin exists).
2
+ // iOS: BGTaskScheduler app-refresh requests; the Info.plist registers the
3
+ // task identifier and UIBackgroundModes fetch. Android: WorkManager periodic
4
+ // requests through platforms/android Gradle deps; the Worker dispatches to
5
+ // the TaskRunner registered below while a runtime is warm.
6
+ //
7
+ // defineTask bodies must be registered at module scope — the OS can invoke a
8
+ // task before app code runs again, and a relaunch only re-evaluates module
9
+ // top-level. That placement is also Apple's registration window: launch
10
+ // handlers must be registered before app launch finishes, and a second
11
+ // registration of the same identifier kills the app. defineTask therefore
12
+ // owns iOS handler registration (once per identifier); register/unregister
13
+ // only submit or cancel refresh requests and are safe to repeat.
14
+ import { isIOS, Utils } from '@nativescript/core'
15
+ import type { BackgroundTasks, TaskContext, TaskExecutor, TaskResult, TaskStatus } from './types'
16
+
17
+ declare const BGTaskScheduler: any
18
+ declare const BGAppRefreshTaskRequest: any
19
+ declare const interop: any
20
+
21
+ const executors = new Map<string, TaskExecutor>()
22
+ const registered = new Map<string, number>()
23
+ const handledIdentifiers = new Set<string>()
24
+ const handlerReady = new Set<string>()
25
+
26
+ const TASK_PREFIX = 'com.octanexplat.tasks.'
27
+
28
+ async function runTask(name: string, context: TaskContext): Promise<TaskResult> {
29
+ const executor = executors.get(name)
30
+
31
+ if (!executor) {
32
+ return 'failed'
33
+ }
34
+
35
+ try {
36
+ return (await executor(context)) ?? 'success'
37
+ } catch {
38
+ return 'failed'
39
+ }
40
+ }
41
+
42
+ // iOS: submit (or replace) the pending refresh request for a task. Each
43
+ // request is consumed by one run, so enable/reschedule and the post-run
44
+ // resubmission share this path. Cancelling first keeps repeated calls
45
+ // idempotent — submitting over a pending request can fail with
46
+ // BGTaskSchedulerErrorCodeTooManyPendingTaskRequests. Submitting without a
47
+ // registered launch handler is not a soft failure: BGTaskScheduler raises an
48
+ // uncatchable NSInternalInconsistencyException that kills the process, so the
49
+ // ready check is a hard gate.
50
+ function iosSubmit(name: string): void {
51
+ const identifier = TASK_PREFIX + name
52
+
53
+ if (!handlerReady.has(name)) {
54
+ throw new Error(
55
+ `backgroundTasks.register: '${name}' has no registered iOS launch handler — ` +
56
+ `its defineTask must run at module scope so registration finishes before app launch completes`,
57
+ )
58
+ }
59
+
60
+ BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(identifier)
61
+
62
+ const request = BGAppRefreshTaskRequest.alloc().initWithIdentifier(identifier)
63
+ const interval = registered.get(name)
64
+
65
+ if (interval) {
66
+ request.earliestBeginDate = (globalThis as any).NSDate.dateWithTimeIntervalSinceNow(interval)
67
+ }
68
+
69
+ const errorRef = typeof interop !== 'undefined' ? new interop.Reference() : null
70
+ const submitted = BGTaskScheduler.sharedScheduler.submitTaskRequestError(request, errorRef)
71
+
72
+ if (!submitted) {
73
+ const detail = errorRef?.value?.localizedDescription ?? 'unknown scheduler error'
74
+
75
+ throw new Error(
76
+ `backgroundTasks.register: refresh request for '${name}' was rejected — ${detail}. ` +
77
+ `Confirm ${identifier} is in BGTaskSchedulerPermittedIdentifiers and UIBackgroundModes includes fetch`,
78
+ )
79
+ }
80
+ }
81
+
82
+ // iOS BGTaskScheduler launch handler — the OS calls the registered handler on
83
+ // a background thread; we resolve via the JS executor, report its real outcome
84
+ // then resubmit the request while the task stays registered. Completion and
85
+ // expiration funnel through one flag: whichever reaches the OS first marks the
86
+ // task exactly once, and a late executor result is discarded.
87
+ function iosHandle(task: any): void {
88
+ const identifier: string = task?.identifier ?? ''
89
+ const name = identifier.startsWith(TASK_PREFIX)
90
+ ? identifier.slice(TASK_PREFIX.length)
91
+ : identifier
92
+
93
+ let expired = false
94
+ let completed = false
95
+ const complete = (success: boolean) => {
96
+ if (completed) {
97
+ return
98
+ }
99
+
100
+ completed = true
101
+ try {
102
+ task.setTaskCompletedWithSuccess(success)
103
+ } catch {}
104
+
105
+ // Requests are single-shot — this run consumed it. Resubmit while the
106
+ // task stays registered so refresh recurs; a run that ended by
107
+ // expiration still leaves the schedule alive.
108
+ if (registered.has(name)) {
109
+ try {
110
+ iosSubmit(name)
111
+ } catch {}
112
+ }
113
+ }
114
+
115
+ task.expirationHandler = () => {
116
+ expired = true
117
+ // The OS is reclaiming the run. The executor may still be mid-flight —
118
+ // signal it cooperatively and complete now; waiting for it risks the
119
+ // process being terminated with the task never marked finished.
120
+ complete(false)
121
+ }
122
+
123
+ const context: TaskContext = {
124
+ name,
125
+ get expired() {
126
+ return expired
127
+ },
128
+ }
129
+
130
+ runTask(name, context).then(
131
+ (result) => complete(result === 'success'),
132
+ () => complete(false),
133
+ )
134
+ }
135
+
136
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
137
+ export const backgroundTasks: BackgroundTasks = {
138
+ supported: isIOS ? typeof BGTaskScheduler !== 'undefined' : true,
139
+
140
+ defineTask(name: string, executor: TaskExecutor): void {
141
+ executors.set(name, executor)
142
+ // iOS: Apple's launch-handler registration. Module scope is already the
143
+ // contract, which is exactly Apple's "before app launch finishes" window.
144
+ // Registration is once per identifier — a second registration of the
145
+ // same identifier kills the app, so a failure is never retried. An
146
+ // "already registered" failure still marks the identifier ready: a module
147
+ // re-eval (hot reload) finds the handler the first evaluation registered.
148
+ if (isIOS && typeof BGTaskScheduler !== 'undefined' && !handledIdentifiers.has(name)) {
149
+ handledIdentifiers.add(name)
150
+ try {
151
+ const registeredHandler =
152
+ BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifierUsingQueueLaunchHandler(
153
+ TASK_PREFIX + name,
154
+ null,
155
+ iosHandle,
156
+ )
157
+
158
+ if (registeredHandler) {
159
+ handlerReady.add(name)
160
+ }
161
+ } catch (error) {
162
+ if (/already been registered/i.test(String(error))) {
163
+ handlerReady.add(name)
164
+ }
165
+ }
166
+ }
167
+ },
168
+
169
+ async register(name: string, options?: { minimumInterval?: number }): Promise<void> {
170
+ if (!executors.has(name)) {
171
+ throw new Error(
172
+ `backgroundTasks.register: '${name}' has no defineTask — declare it at module scope`,
173
+ )
174
+ }
175
+
176
+ if (isIOS) {
177
+ if (typeof BGTaskScheduler === 'undefined') {
178
+ throw new Error('unsupported: BGTaskScheduler is not available')
179
+ }
180
+
181
+ registered.set(name, options?.minimumInterval ?? 0)
182
+ try {
183
+ iosSubmit(name)
184
+ } catch (error) {
185
+ registered.delete(name)
186
+ throw error
187
+ }
188
+
189
+ return
190
+ }
191
+
192
+ // Android: WorkManager — the Java side reads the registered map off the
193
+ // global so a cold start rebuilds scheduled work from defineTask calls.
194
+ // `Utils.android` is a {} stub off Android, so the context stays absent
195
+ // and scheduling is skipped there.
196
+ const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
197
+ const context = (Utils.android as any)?.getApplicationContext?.()
198
+
199
+ if (worker?.schedule && context) {
200
+ worker.schedule(context, name, options?.minimumInterval ?? 0)
201
+ }
202
+
203
+ registered.set(name, options?.minimumInterval ?? 0)
204
+ },
205
+
206
+ async unregister(name: string): Promise<void> {
207
+ registered.delete(name)
208
+ if (isIOS) {
209
+ BGTaskScheduler.sharedScheduler?.cancelTaskRequestWithIdentifier?.(TASK_PREFIX + name)
210
+ return
211
+ }
212
+
213
+ const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
214
+ const context = (Utils.android as any)?.getApplicationContext?.()
215
+
216
+ if (context) {
217
+ worker?.cancel?.(context, name)
218
+ }
219
+ },
220
+
221
+ async getStatus(): Promise<TaskStatus> {
222
+ if (isIOS) {
223
+ if (typeof BGTaskScheduler === 'undefined') {
224
+ return 'unavailable'
225
+ }
226
+
227
+ const status = (globalThis as any).UIApplication?.sharedApplication?.backgroundRefreshStatus
228
+
229
+ // UIBackgroundRefreshStatus: 0 restricted, 1 denied, 2 available
230
+ return status === 0 || status === 1 ? 'restricted' : 'available'
231
+ }
232
+
233
+ return 'available'
234
+ },
235
+
236
+ async isRegistered(name: string): Promise<boolean> {
237
+ return registered.has(name)
238
+ },
239
+ }
240
+
241
+ // Worker → JS entry. Android's TaskWorker invokes the TaskRunner registered
242
+ // at module evaluation — calls from the worker thread dispatch onto the JS
243
+ // thread, then the worker blocks on TaskOutcome until the executor settles.
244
+ const taskWorker = (globalThis as any).com?.octanexplat?.tasks?.TaskWorker
245
+
246
+ if (!isIOS && typeof taskWorker?.setTaskRunner === 'function') {
247
+ taskWorker.setTaskRunner(
248
+ new taskWorker.TaskRunner({
249
+ run(name: string, outcome: { onResult(r: string): void }) {
250
+ const report = (r: string) => {
251
+ try {
252
+ outcome.onResult(r)
253
+ } catch {}
254
+ }
255
+
256
+ runTask(name, { name, expired: false }).then(report, () => report('failed'))
257
+ },
258
+ }),
259
+ )
260
+ }
@@ -0,0 +1,15 @@
1
+ // Background tasks — no reliable web equivalent (Periodic Background Sync is
2
+ // Chromium-only + requires an installed PWA). Honest unsupported leaf.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () => Promise.reject(new Error('unsupported: no background task API on web'))
6
+
7
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
8
+ export const backgroundTasks: BackgroundTasks = {
9
+ supported: false,
10
+ defineTask: () => {},
11
+ register: unsupported,
12
+ unregister: unsupported,
13
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
14
+ isRegistered: async () => false,
15
+ }
@@ -0,0 +1,16 @@
1
+ // Unsupported leaf — platform-specific schedulers (NSBackgroundActivityScheduler
2
+ // on macOS) are follow-ups; the API surface stands.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () =>
6
+ Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
7
+
8
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
9
+ export const backgroundTasks: BackgroundTasks = {
10
+ supported: false,
11
+ defineTask: () => {},
12
+ register: unsupported,
13
+ unregister: unsupported,
14
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
+ isRegistered: async () => false,
16
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { backgroundTasks } from './background-tasks.macos'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { backgroundTasks } from './background-tasks'
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { backgroundTasks } from './background-tasks.web'
package/src/types.ts ADDED
@@ -0,0 +1,57 @@
1
+ /** Reported outcome of a task run — the OS uses it for scheduling heuristics
2
+ * (repeated 'failed' runs get deferred on both stores). */
3
+ export type TaskResult = 'success' | 'failed'
4
+
5
+ /** Invocation payload handed to a TaskExecutor. */
6
+ export interface TaskContext {
7
+ /** The registered task name — one executor may serve several names. */
8
+ name: string
9
+ /** true once the OS has reclaimed the run's time budget (the iOS
10
+ * expiration handler). Cancellation is cooperative: the executor cannot
11
+ * be preempted, so check this between awaits and resolve promptly. The
12
+ * task is already being completed as failed — a late result is
13
+ * discarded. Always false on platforms without an expiration concept. */
14
+ readonly expired: boolean
15
+ }
16
+
17
+ /** The task body; resolves 'success' | 'failed' for OS scheduling feedback. */
18
+ export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>
19
+
20
+ /** OS willingness to run background tasks — 'restricted' means the user or
21
+ * a battery/data saver mode has throttled them; 'unavailable' means the
22
+ * platform has no background-task path at all. */
23
+ export type TaskStatus = 'available' | 'restricted' | 'unavailable'
24
+
25
+ /** Background-task façade. Tasks are defined at module scope, then
26
+ * enabled/disabled against the OS scheduler (iOS BGTaskScheduler /
27
+ * Android WorkManager-style periodic work). Intervals are minimums — the OS
28
+ * decides actual timing. */
29
+ export interface BackgroundTasks {
30
+ /** Synchronous fast check — a background-task scheduler exists. */
31
+ readonly supported: boolean
32
+ /** Define a task at module scope — the OS may invoke the name before any
33
+ * other call, so registration must be load-time (expo-task-manager's
34
+ * structural constraint, mirrored deliberately). On iOS this is also
35
+ * Apple's launch-handler registration, which must finish before app
36
+ * launch completes and is registered once per task for the process'
37
+ * lifetime — module scope is what makes both requirements safe. */
38
+ defineTask(name: string, executor: TaskExecutor): void
39
+ /** Enable or reschedule a defined task by submitting the next refresh
40
+ * request. Idempotent — a repeated call replaces the pending request, so
41
+ * it is safe to call at every launch or from an enable action. iOS
42
+ * requests are single-shot: the scheduler resubmits after each run while
43
+ * the task stays enabled. `minimumInterval` is a hint in scheduler units
44
+ * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
45
+ * and may defer well past it. */
46
+ register(name: string, options?: { minimumInterval?: number }): Promise<void>
47
+ /** Cancel a previously enabled task's pending request; no-op when not
48
+ * enabled. Does not interrupt an executor already running. */
49
+ unregister(name: string): Promise<void>
50
+ /** Current OS scheduling posture for this app. */
51
+ getStatus(): Promise<TaskStatus>
52
+ /** Whether `name` is enabled in this process — an in-memory record, not a
53
+ * query of the OS's durable request queue. */
54
+ isRegistered(name: string): Promise<boolean>
55
+ }
56
+
57
+ export declare const backgroundTasks: BackgroundTasks
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "background-tasks.d.ts",
5
+ "index.d.ts",
6
+ "types.d.ts"
7
+ ]
8
+ }
@@ -0,0 +1,3 @@
1
+ import type { BackgroundTasks } from './types.js';
2
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
3
+ export declare const backgroundTasks: BackgroundTasks;
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { backgroundTasks } from './background-tasks.js';
@@ -0,0 +1,54 @@
1
+ /** Reported outcome of a task run — the OS uses it for scheduling heuristics
2
+ * (repeated 'failed' runs get deferred on both stores). */
3
+ export type TaskResult = 'success' | 'failed';
4
+ /** Invocation payload handed to a TaskExecutor. */
5
+ export interface TaskContext {
6
+ /** The registered task name — one executor may serve several names. */
7
+ name: string;
8
+ /** true once the OS has reclaimed the run's time budget (the iOS
9
+ * expiration handler). Cancellation is cooperative: the executor cannot
10
+ * be preempted, so check this between awaits and resolve promptly. The
11
+ * task is already being completed as failed — a late result is
12
+ * discarded. Always false on platforms without an expiration concept. */
13
+ readonly expired: boolean;
14
+ }
15
+ /** The task body; resolves 'success' | 'failed' for OS scheduling feedback. */
16
+ export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>;
17
+ /** OS willingness to run background tasks — 'restricted' means the user or
18
+ * a battery/data saver mode has throttled them; 'unavailable' means the
19
+ * platform has no background-task path at all. */
20
+ export type TaskStatus = 'available' | 'restricted' | 'unavailable';
21
+ /** Background-task façade. Tasks are defined at module scope, then
22
+ * enabled/disabled against the OS scheduler (iOS BGTaskScheduler /
23
+ * Android WorkManager-style periodic work). Intervals are minimums — the OS
24
+ * decides actual timing. */
25
+ export interface BackgroundTasks {
26
+ /** Synchronous fast check — a background-task scheduler exists. */
27
+ readonly supported: boolean;
28
+ /** Define a task at module scope — the OS may invoke the name before any
29
+ * other call, so registration must be load-time (expo-task-manager's
30
+ * structural constraint, mirrored deliberately). On iOS this is also
31
+ * Apple's launch-handler registration, which must finish before app
32
+ * launch completes and is registered once per task for the process'
33
+ * lifetime — module scope is what makes both requirements safe. */
34
+ defineTask(name: string, executor: TaskExecutor): void;
35
+ /** Enable or reschedule a defined task by submitting the next refresh
36
+ * request. Idempotent — a repeated call replaces the pending request, so
37
+ * it is safe to call at every launch or from an enable action. iOS
38
+ * requests are single-shot: the scheduler resubmits after each run while
39
+ * the task stays enabled. `minimumInterval` is a hint in scheduler units
40
+ * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
41
+ * and may defer well past it. */
42
+ register(name: string, options?: {
43
+ minimumInterval?: number;
44
+ }): Promise<void>;
45
+ /** Cancel a previously enabled task's pending request; no-op when not
46
+ * enabled. Does not interrupt an executor already running. */
47
+ unregister(name: string): Promise<void>;
48
+ /** Current OS scheduling posture for this app. */
49
+ getStatus(): Promise<TaskStatus>;
50
+ /** Whether `name` is enabled in this process — an in-memory record, not a
51
+ * query of the OS's durable request queue. */
52
+ isRegistered(name: string): Promise<boolean>;
53
+ }
54
+ export declare const backgroundTasks: BackgroundTasks;