@uru-intelligence/app 1.0.0 → 2.1.0

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/dist/files.js ADDED
@@ -0,0 +1,149 @@
1
+ import { UruAppRuntimeError } from './errors.js';
2
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
3
+ import { isRuntimeJsonObject } from './transport-json.js';
4
+ const LIBRARY_READ_BYTES = 5 * 1024 * 1024;
5
+ const OUTPUT_BYTES = 10 * 1024 * 1024;
6
+ const RESPONSE_BYTES = Math.ceil(OUTPUT_BYTES / 3) * 4 + 8192;
7
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ const HASH = /^[0-9a-f]{64}$/;
9
+ function invalid() {
10
+ throw new UruAppRuntimeError('Invalid file request or response.', { status: 0, body: null });
11
+ }
12
+ const identifier = (value) => typeof value === 'string' && UUID.test(value) ? value : invalid();
13
+ const object = (value) => isRuntimeJsonObject(value) ? value : invalid();
14
+ const string = (value) => typeof value === 'string' ? value : invalid();
15
+ function metadata(value, maxBytes) {
16
+ const sizeBytes = value['sizeBytes'];
17
+ const filename = string(value['filename']);
18
+ const contentType = string(value['contentType']);
19
+ const sha256 = string(value['sha256']);
20
+ if (typeof sizeBytes !== 'number' || !Number.isSafeInteger(sizeBytes) || sizeBytes < 0 || sizeBytes > maxBytes ||
21
+ filename.length < 1 || filename.length > 255 || contentType.length < 1 || contentType.length > 255 || !HASH.test(sha256))
22
+ invalid();
23
+ return { fileId: identifier(string(value['fileId'])), filename, contentType, sizeBytes, sha256 };
24
+ }
25
+ function output(value) {
26
+ const row = object(value);
27
+ const createdAt = string(row['createdAt']);
28
+ if (!Number.isFinite(Date.parse(createdAt)))
29
+ invalid();
30
+ return { ...metadata(row, OUTPUT_BYTES), outputId: identifier(string(row['outputId'])), createdAt };
31
+ }
32
+ function content(value, maxBytes) {
33
+ const row = object(value);
34
+ const meta = metadata(row, maxBytes);
35
+ const encoded = string(row['contentBase64']);
36
+ if (encoded.length > Math.ceil(maxBytes / 3) * 4 ||
37
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))
38
+ invalid();
39
+ let decoded;
40
+ try {
41
+ decoded = atob(encoded);
42
+ }
43
+ catch {
44
+ return invalid();
45
+ }
46
+ if (decoded.length !== meta.sizeBytes)
47
+ invalid();
48
+ return { ...meta, content: Uint8Array.from(decoded, character => character.charCodeAt(0)) };
49
+ }
50
+ function base64(bytes) {
51
+ let binary = '';
52
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
53
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
54
+ }
55
+ return btoa(binary);
56
+ }
57
+ async function readJson(response) {
58
+ const reader = response.body?.getReader();
59
+ if (reader === undefined)
60
+ invalid();
61
+ const decoder = new TextDecoder();
62
+ let size = 0;
63
+ let text = '';
64
+ try {
65
+ for (;;) {
66
+ const chunk = await reader.read();
67
+ if (chunk.done)
68
+ break;
69
+ size += chunk.value.byteLength;
70
+ if (size > RESPONSE_BYTES) {
71
+ await reader.cancel();
72
+ invalid();
73
+ }
74
+ text += decoder.decode(chunk.value, { stream: true });
75
+ }
76
+ text += decoder.decode();
77
+ return JSON.parse(text);
78
+ }
79
+ catch (error) {
80
+ if (error instanceof UruAppRuntimeError)
81
+ throw error;
82
+ return invalid();
83
+ }
84
+ finally {
85
+ reader.releaseLock();
86
+ }
87
+ }
88
+ export function createFilesContext(options) {
89
+ const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/files`;
90
+ const request = async (path, payload, signal) => {
91
+ const headers = new Headers(await resolveHeaders(options.headers));
92
+ if (payload !== undefined)
93
+ headers.set('content-type', 'application/json');
94
+ const response = await (options.fetch ?? globalThis.fetch)(`${base}${path}`, {
95
+ method: payload === undefined ? 'GET' : 'POST', headers,
96
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
97
+ signal: signal === undefined ? AbortSignal.timeout(30_000) : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
98
+ });
99
+ if (!response.ok) {
100
+ await response.body?.cancel();
101
+ throw new UruAppRuntimeError('File access was not accepted.', { status: response.status, body: null });
102
+ }
103
+ return readJson(response);
104
+ };
105
+ return {
106
+ read: async (fileId, settings) => content(await request(`/${identifier(fileId)}`, undefined, settings?.signal), LIBRARY_READ_BYTES),
107
+ readOutput: async (outputId, settings) => content(await request(`/outputs/${identifier(outputId)}`, undefined, settings?.signal), OUTPUT_BYTES),
108
+ createOutput: async (input) => {
109
+ if (!(input.content instanceof Uint8Array) || input.content.byteLength > OUTPUT_BYTES ||
110
+ typeof input.name !== 'string' || typeof input.contentType !== 'string' || typeof input.idempotencyKey !== 'string' ||
111
+ input.name.trim().length < 1 || input.name.length > 255 ||
112
+ input.contentType.trim().length < 1 || input.contentType.length > 255 ||
113
+ input.idempotencyKey.trim().length < 1 || input.idempotencyKey.length > 128 ||
114
+ (input.sha256 !== undefined && !HASH.test(input.sha256)))
115
+ invalid();
116
+ return output(await request('/outputs', {
117
+ name: input.name, contentType: input.contentType, contentBase64: base64(input.content),
118
+ idempotencyKey: input.idempotencyKey,
119
+ ...(input.sha256 === undefined ? {} : { sha256: input.sha256 }),
120
+ }, input.signal));
121
+ },
122
+ listOutputs: async (settings = {}) => {
123
+ if (settings.limit !== undefined && (!Number.isInteger(settings.limit) || settings.limit < 1 || settings.limit > 100))
124
+ invalid();
125
+ if (settings.cursor !== undefined && (typeof settings.cursor !== 'string' || settings.cursor.length === 0 || settings.cursor.length > 4096))
126
+ invalid();
127
+ const params = new URLSearchParams();
128
+ if (settings.cursor !== undefined)
129
+ params.set('cursor', settings.cursor);
130
+ if (settings.limit !== undefined)
131
+ params.set('limit', String(settings.limit));
132
+ const result = object(await request(`/outputs${params.size === 0 ? '' : `?${params}`}`, undefined, settings.signal));
133
+ const values = result['items'];
134
+ if (!Array.isArray(values) || values.length > (settings.limit ?? 100))
135
+ invalid();
136
+ const items = values.map(value => {
137
+ const row = object(value);
138
+ return { ...output(row),
139
+ releaseId: row['releaseId'] === null ? null : identifier(string(row['releaseId'])),
140
+ buildId: row['buildId'] === null ? null : identifier(string(row['buildId'])),
141
+ };
142
+ });
143
+ const nextCursor = result['nextCursor'] === null ? null : string(result['nextCursor']);
144
+ if (nextCursor !== null && (nextCursor.length === 0 || nextCursor.length > 4096))
145
+ invalid();
146
+ return { items, nextCursor };
147
+ },
148
+ };
149
+ }
package/dist/index.d.ts CHANGED
@@ -5,24 +5,27 @@
5
5
  * promise to every project that installs it, so the barrel is deliberately
6
6
  * small: one error class, two factories, and the types a caller needs to name
7
7
  * what they get back. Internal helpers live in `./runtime.js`, `./transport.js`,
8
- * `./dampers.js` and `./errorResponse.js` and are not re-exported.
8
+ * `./dampers.js` and `./error-response.js` and are not re-exported.
9
9
  *
10
10
  * Adding an export here is an API decision. Removing one is a breaking change.
11
11
  */
12
- import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeClient, UruProviderRuntimeEnvironment, UruServerContext } from './types.js';
13
- export { UruAppRuntimeError } from './errors.js';
14
- export type { UruRunawayDamperOptions } from './dampers.js';
15
- export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowsResult, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruProviderRuntimeEnvironment, UruServerContext, } from './types.js';
12
+ import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeClient, UruProviderRuntimeEnvironment, UruServerContext } from "./types.js";
13
+ export { UruAppRuntimeError } from "./errors.js";
14
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
15
+ export type { UruRunawayDamperOptions } from "./dampers.js";
16
+ export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowsResult, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruProviderRuntimeEnvironment, UruServerContext, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadsContext, } from "./types.js";
16
17
  /**
17
18
  * Build a capability-invocation client against a Uru app runtime.
18
19
  *
19
- * Most apps want {@link createUruServerContext} instead, which reads the
20
- * provider bindings out of the environment and adds Datasets, actions, jobs and
21
- * secrets on top. Use this directly when the caller already knows its
22
- * deployment id and how to authenticate — a browser calling a public page's
23
- * runtime, for example.
20
+ * {@link createUruServerContext} is the easier way to get one from a request
21
+ * handler's own environment bindings, and it also adds Datasets, actions,
22
+ * jobs and secrets on top — but only where a runtime token actually reaches
23
+ * that handler (see its own doc comment; a serverful Gem's request handler is
24
+ * the one place it never does). Use this directly when the caller already
25
+ * knows its deployment id and how to authenticate — a browser calling a
26
+ * public page's runtime, for example.
24
27
  */
25
- export declare function createUruAppRuntimeClient(options: CreateUruAppRuntimeClientOptions): UruAppRuntimeClient;
28
+ export declare const createUruAppRuntimeClient: (options: CreateUruAppRuntimeClientOptions) => UruAppRuntimeClient;
26
29
  /**
27
30
  * Build the server context a Uru app runs against, from the provider bindings
28
31
  * in `env`.
@@ -31,5 +34,18 @@ export declare function createUruAppRuntimeClient(options: CreateUruAppRuntimeCl
31
34
  * required and are injected by the Uru runtime. A missing one throws
32
35
  * {@link UruAppRuntimeError} naming the binding, rather than failing later at a
33
36
  * request that could not have worked.
37
+ *
38
+ * **Not every hosting class carries `URU_RUNTIME_TOKEN` at request time, so
39
+ * this does not run everywhere a Gem's own code runs:**
40
+ *
41
+ * - A Cloudflare Worker Gem always has it, at every request.
42
+ * - A serverful (Fly) Gem's REQUEST HANDLER never does. The token is
43
+ * deliberately left out of that deployment's environment, and the guest
44
+ * refuses to even boot if one is somehow present — so calling this from a
45
+ * Fly `server_web_app` request handler throws every time, not just
46
+ * sometimes. Do the work in a program job instead.
47
+ * - A program job is unaffected either way: it runs on its own dedicated
48
+ * Machine, which is provisioned with its own token regardless of the app's
49
+ * hosting class.
34
50
  */
35
- export declare function createUruServerContext(env: UruProviderRuntimeEnvironment, options?: CreateUruServerContextOptions): UruServerContext;
51
+ export declare const createUruServerContext: (env: UruProviderRuntimeEnvironment, options?: CreateUruServerContextOptions) => UruServerContext;
package/dist/index.js CHANGED
@@ -5,48 +5,76 @@
5
5
  * promise to every project that installs it, so the barrel is deliberately
6
6
  * small: one error class, two factories, and the types a caller needs to name
7
7
  * what they get back. Internal helpers live in `./runtime.js`, `./transport.js`,
8
- * `./dampers.js` and `./errorResponse.js` and are not re-exported.
8
+ * `./dampers.js` and `./error-response.js` and are not re-exported.
9
9
  *
10
10
  * Adding an export here is an API decision. Removing one is a breaking change.
11
11
  */
12
- import { createDatasetsContext } from './datasets.js';
13
- import { ForceRefreshThrottle, resolveDamperConfig } from './dampers.js';
14
- import { UruAppRuntimeError } from './errors.js';
15
- import { requireCompletedRuntimeResponse } from './runtime.js';
16
- import { cancelAppRuntimeJob, getAppRuntimeJobStatus, invokeAppRuntime, } from './transport.js';
17
- export { UruAppRuntimeError } from './errors.js';
18
- /** Read a required runtime binding, or throw naming the one that is missing. */
19
- function requiredRuntimeEnv(env, key) {
20
- const value = String(env[key] ?? '').trim();
21
- if (!value) {
12
+ import { ForceRefreshThrottle, resolveDamperConfig } from "./dampers.js";
13
+ import { createDatasetsContext } from "./datasets.js";
14
+ import { createFilesContext } from './files.js';
15
+ import { createJobProgress, createJobCheckpoint } from './jobs.js';
16
+ import { UruAppRuntimeError } from "./errors.js";
17
+ import { createActionInvoker, createCancelJobInvoker, createCapabilityInvoker, createJobStatusInvoker, } from "./invocations.js";
18
+ export { UruAppRuntimeError } from "./errors.js";
19
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
20
+ const ownEnvironmentValue = (env, key) => {
21
+ if (!Object.hasOwn(env, key)) {
22
+ return undefined;
23
+ }
24
+ const value = env[key];
25
+ return typeof value === "string" ? value : undefined;
26
+ };
27
+ /**
28
+ * Read a required runtime binding, or throw naming the one that is missing.
29
+ *
30
+ * `URU_RUNTIME_TOKEN` gets its own message: on a serverful (Fly) Gem's
31
+ * request handler, this binding is not merely unset by accident — that
32
+ * hosting class never carries it at request time (see
33
+ * {@link createUruServerContext}'s own doc comment for exactly which classes
34
+ * do), so "missing" would read as a fixable configuration bug when it is
35
+ * actually the platform's own design.
36
+ */
37
+ const requiredRuntimeEnv = (env, key) => {
38
+ const value = (ownEnvironmentValue(env, key) ?? "").trim();
39
+ if (value === "") {
40
+ if (key === "URU_RUNTIME_TOKEN") {
41
+ throw new UruAppRuntimeError("This hosting class does not carry a runtime token at request time, " +
42
+ "so createUruServerContext cannot run here. A serverful (Fly) Gem's " +
43
+ "request handler never receives one, by design; a Cloudflare Worker " +
44
+ "Gem always does. If this code needs platform capabilities, run it " +
45
+ "from a program job instead — a program job runs on its own " +
46
+ "dedicated Machine with its own token, regardless of hosting class.", { body: null, status: 0 });
47
+ }
22
48
  throw new UruAppRuntimeError(`Missing Uru runtime binding: ${key}`, {
23
- status: 0,
24
49
  body: null,
50
+ status: 0,
25
51
  });
26
52
  }
27
53
  return value;
28
- }
54
+ };
29
55
  /** Reject an empty secret name before it becomes an empty env lookup. */
30
- function normalizedSecretName(name) {
31
- const normalized = String(name ?? '').trim();
32
- if (!normalized) {
33
- throw new UruAppRuntimeError('Uru app secret name is required.', {
34
- status: 0,
56
+ const normalizedSecretName = (name) => {
57
+ const normalized = name.trim();
58
+ if (normalized === "") {
59
+ throw new UruAppRuntimeError("Uru app secret name is required.", {
35
60
  body: null,
61
+ status: 0,
36
62
  });
37
63
  }
38
64
  return normalized;
39
- }
65
+ };
40
66
  /**
41
67
  * Build a capability-invocation client against a Uru app runtime.
42
68
  *
43
- * Most apps want {@link createUruServerContext} instead, which reads the
44
- * provider bindings out of the environment and adds Datasets, actions, jobs and
45
- * secrets on top. Use this directly when the caller already knows its
46
- * deployment id and how to authenticate — a browser calling a public page's
47
- * runtime, for example.
69
+ * {@link createUruServerContext} is the easier way to get one from a request
70
+ * handler's own environment bindings, and it also adds Datasets, actions,
71
+ * jobs and secrets on top — but only where a runtime token actually reaches
72
+ * that handler (see its own doc comment; a serverful Gem's request handler is
73
+ * the one place it never does). Use this directly when the caller already
74
+ * knows its deployment id and how to authenticate — a browser calling a
75
+ * public page's runtime, for example.
48
76
  */
49
- export function createUruAppRuntimeClient(options) {
77
+ export const createUruAppRuntimeClient = (options) => {
50
78
  // One damper runtime per client: the resolved config plus the forceRefresh
51
79
  // throttle whose per-capability timestamps must persist across calls.
52
80
  const damper = {
@@ -54,15 +82,15 @@ export function createUruAppRuntimeClient(options) {
54
82
  throttle: new ForceRefreshThrottle(),
55
83
  };
56
84
  return {
57
- query: (name, input, invocationOptions) => invokeAppRuntime(options, damper, 'query', name, input, invocationOptions),
58
- action: (name, input, invocationOptions) => invokeAppRuntime(options, damper, 'action', name, input, invocationOptions),
59
- job: (name, input, invocationOptions) => invokeAppRuntime(options, damper, 'job', name, input, invocationOptions),
60
- endpoint: (name, input, invocationOptions) => invokeAppRuntime(options, damper, 'endpoint', name, input, invocationOptions),
61
- serverFunction: (name, input, invocationOptions) => invokeAppRuntime(options, damper, 'server_function', name, input, invocationOptions),
62
- jobStatus: (executionId, invocationOptions) => getAppRuntimeJobStatus(options, executionId, invocationOptions),
63
- cancelJob: (executionId, invocationOptions) => cancelAppRuntimeJob(options, executionId, invocationOptions),
85
+ action: createCapabilityInvoker(options, damper, "action"),
86
+ cancelJob: createCancelJobInvoker(options),
87
+ endpoint: createCapabilityInvoker(options, damper, "endpoint"),
88
+ job: createCapabilityInvoker(options, damper, "job"),
89
+ jobStatus: createJobStatusInvoker(options),
90
+ query: createCapabilityInvoker(options, damper, "query"),
91
+ serverFunction: createCapabilityInvoker(options, damper, "server_function"),
64
92
  };
65
- }
93
+ };
66
94
  /**
67
95
  * Build the server context a Uru app runs against, from the provider bindings
68
96
  * in `env`.
@@ -71,48 +99,63 @@ export function createUruAppRuntimeClient(options) {
71
99
  * required and are injected by the Uru runtime. A missing one throws
72
100
  * {@link UruAppRuntimeError} naming the binding, rather than failing later at a
73
101
  * request that could not have worked.
102
+ *
103
+ * **Not every hosting class carries `URU_RUNTIME_TOKEN` at request time, so
104
+ * this does not run everywhere a Gem's own code runs:**
105
+ *
106
+ * - A Cloudflare Worker Gem always has it, at every request.
107
+ * - A serverful (Fly) Gem's REQUEST HANDLER never does. The token is
108
+ * deliberately left out of that deployment's environment, and the guest
109
+ * refuses to even boot if one is somehow present — so calling this from a
110
+ * Fly `server_web_app` request handler throws every time, not just
111
+ * sometimes. Do the work in a program job instead.
112
+ * - A program job is unaffected either way: it runs on its own dedicated
113
+ * Machine, which is provisioned with its own token regardless of the app's
114
+ * hosting class.
74
115
  */
75
- export function createUruServerContext(env, options = {}) {
76
- const deploymentId = requiredRuntimeEnv(env, 'URU_DEPLOYMENT_ID');
77
- const baseUrl = requiredRuntimeEnv(env, 'URU_RUNTIME_API_BASE');
78
- const runtimeToken = requiredRuntimeEnv(env, 'URU_RUNTIME_TOKEN');
116
+ export const createUruServerContext = (env, options = {}) => {
117
+ const deploymentId = requiredRuntimeEnv(env, "URU_DEPLOYMENT_ID");
118
+ const baseUrl = requiredRuntimeEnv(env, "URU_RUNTIME_API_BASE");
119
+ const runtimeToken = requiredRuntimeEnv(env, "URU_RUNTIME_TOKEN");
79
120
  const clientOptions = {
80
- deploymentId,
81
121
  baseUrl,
82
- providerRuntime: true,
122
+ deploymentId,
83
123
  headers: {
84
- 'x-uru-app-runtime-token': runtimeToken,
124
+ "x-uru-app-runtime-token": runtimeToken,
85
125
  },
126
+ providerRuntime: true,
86
127
  };
87
- if (options.fetch) {
128
+ if (options.fetch !== undefined) {
88
129
  clientOptions.fetch = options.fetch;
89
130
  }
90
131
  const app = createUruAppRuntimeClient(clientOptions);
91
132
  return {
133
+ actions: { run: createActionInvoker(app) },
92
134
  app,
93
135
  datasets: createDatasetsContext(app, clientOptions),
94
- actions: {
95
- run: (name, input, invocationOptions) => requireCompletedRuntimeResponse(app.action(name, input, invocationOptions)),
96
- },
136
+ files: createFilesContext(clientOptions),
97
137
  jobs: {
98
- start: (name, input, invocationOptions) => app.job(name, input, invocationOptions),
138
+ start: app.job,
139
+ progress: createJobProgress(clientOptions, env),
140
+ checkpoint: createJobCheckpoint(clientOptions, env),
99
141
  },
100
142
  secrets: {
101
- has: (name) => {
102
- const key = normalizedSecretName(name);
103
- return String(env[key] ?? '').length > 0;
104
- },
105
143
  get: (name) => {
106
144
  const key = normalizedSecretName(name);
107
- const value = String(env[key] ?? '');
108
- if (!value) {
145
+ const value = ownEnvironmentValue(env, key);
146
+ if (value === undefined || value === "") {
109
147
  throw new UruAppRuntimeError(`Missing Uru app secret binding: ${key}`, {
110
- status: 0,
111
148
  body: null,
149
+ status: 0,
112
150
  });
113
151
  }
114
152
  return value;
115
153
  },
154
+ has: (name) => {
155
+ const key = normalizedSecretName(name);
156
+ const value = ownEnvironmentValue(env, key);
157
+ return value !== undefined && value.length > 0;
158
+ },
116
159
  },
117
160
  };
118
- }
161
+ };
@@ -0,0 +1,7 @@
1
+ import type { DamperRuntime } from "./transport.js";
2
+ import type { CreateUruAppRuntimeClientOptions, UruActionInvoker, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruCapabilityInvoker, UruCancelJobInvoker, UruJobStatusInvoker } from "./types.js";
3
+ /** Overloads expose a typed result only when the transport runs its decoder. */
4
+ export declare const createCapabilityInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType) => UruCapabilityInvoker;
5
+ export declare const createJobStatusInvoker: (options: CreateUruAppRuntimeClientOptions) => UruJobStatusInvoker;
6
+ export declare const createCancelJobInvoker: (options: CreateUruAppRuntimeClientOptions) => UruCancelJobInvoker;
7
+ export declare const createActionInvoker: (app: UruAppRuntimeClient) => UruActionInvoker;
@@ -0,0 +1,27 @@
1
+ import { requireCompletedRuntimeResponse } from "./runtime.js";
2
+ import { cancelAppRuntimeJob, getAppRuntimeJobStatus, invokeAppRuntime, } from "./transport.js";
3
+ /** Overloads expose a typed result only when the transport runs its decoder. */
4
+ export const createCapabilityInvoker = (options, damper, capabilityType) => {
5
+ async function invoke(name, input, invocationOptions) {
6
+ return await invokeAppRuntime(options, damper, capabilityType, name, input, invocationOptions);
7
+ }
8
+ return invoke;
9
+ };
10
+ export const createJobStatusInvoker = (options) => {
11
+ async function status(executionId, invocationOptions) {
12
+ return await getAppRuntimeJobStatus(options, executionId, invocationOptions);
13
+ }
14
+ return status;
15
+ };
16
+ export const createCancelJobInvoker = (options) => {
17
+ async function cancel(executionId, invocationOptions) {
18
+ return await cancelAppRuntimeJob(options, executionId, invocationOptions);
19
+ }
20
+ return cancel;
21
+ };
22
+ export const createActionInvoker = (app) => {
23
+ async function run(name, input, invocationOptions) {
24
+ return await requireCompletedRuntimeResponse(app.action(name, input, invocationOptions));
25
+ }
26
+ return run;
27
+ };
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { RuntimeJsonObject } from './transport-json.js';
2
+ import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment } from './types.js';
3
+ export declare const createJobProgress: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (progress: UruJobProgress) => Promise<void>;
4
+ export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (value: RuntimeJsonObject) => Promise<void>;
package/dist/jobs.js ADDED
@@ -0,0 +1,35 @@
1
+ import { UruAppRuntimeError } from './errors.js';
2
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
3
+ import { isRuntimeJsonObject } from './transport-json.js';
4
+ const postJobUpdate = async (options, env, operation, payload) => {
5
+ const runId = Object.hasOwn(env, 'URU_JOB_RUN_ID') ? env['URU_JOB_RUN_ID']?.trim() : undefined;
6
+ const attemptId = Object.hasOwn(env, 'URU_JOB_ATTEMPT_ID') ? env['URU_JOB_ATTEMPT_ID']?.trim() : undefined;
7
+ if (!runId || !attemptId) {
8
+ throw new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
9
+ }
10
+ const headers = new Headers(await resolveHeaders(options.headers));
11
+ headers.set('content-type', 'application/json');
12
+ const url = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/jobs/executions/${encodeURIComponent(runId)}/attempts/${encodeURIComponent(attemptId)}/${operation}`;
13
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
14
+ method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000),
15
+ });
16
+ if (!response.ok) {
17
+ await response.body?.cancel();
18
+ throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
19
+ }
20
+ await response.body?.cancel();
21
+ };
22
+ export const createJobProgress = (options, env) => async (progress) => {
23
+ if (!Number.isSafeInteger(progress.completed) || progress.completed < 0 ||
24
+ (progress.total !== undefined && (!Number.isSafeInteger(progress.total) || progress.total < progress.completed)) ||
25
+ (progress.message !== undefined && typeof progress.message !== 'string')) {
26
+ throw new UruAppRuntimeError('Invalid job progress.', { status: 0, body: null });
27
+ }
28
+ await postJobUpdate(options, env, 'progress', progress);
29
+ };
30
+ export const createJobCheckpoint = (options, env) => async (value) => {
31
+ if (!isRuntimeJsonObject(value)) {
32
+ throw new UruAppRuntimeError('A job checkpoint must contain JSON data.', { status: 0, body: null });
33
+ }
34
+ await postJobUpdate(options, env, 'checkpoint', { value });
35
+ };
package/dist/runtime.d.ts CHANGED
@@ -11,17 +11,17 @@
11
11
  *
12
12
  * Imports `./errors.js` and `./types.js`, both of which import nothing back.
13
13
  */
14
- import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeInvocationResponse } from './types.js';
14
+ import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeInvocationResponse } from "./types.js";
15
15
  /** Drop one trailing `/` so a base URL concatenates cleanly with a rooted path. */
16
- export declare function trimTrailingSlash(value: string): string;
16
+ export declare const trimTrailingSlash: (value: string) => string;
17
17
  /**
18
18
  * The rooted path every runtime call hangs off, in precedence order: a public
19
19
  * page's own runtime, then the provider runtime, then an explicit override,
20
20
  * then the default in-app route.
21
21
  */
22
- export declare function runtimeBasePath(options: CreateUruAppRuntimeClientOptions): string;
22
+ export declare const runtimeBasePath: (options: CreateUruAppRuntimeClientOptions) => string;
23
23
  /** Resolve the caller's headers, awaiting them when they are supplied lazily. */
24
- export declare function resolveHeaders(headers: CreateUruAppRuntimeClientOptions['headers']): Promise<HeadersInit | undefined>;
24
+ export declare const resolveHeaders: (headers: CreateUruAppRuntimeClientOptions["headers"]) => Promise<HeadersInit | undefined>;
25
25
  /**
26
26
  * Narrow an invocation response to its result, or throw.
27
27
  *
@@ -29,4 +29,4 @@ export declare function resolveHeaders(headers: CreateUruAppRuntimeClientOptions
29
29
  * the caller wants the value and a pending or failed call is an error rather
30
30
  * than a state to render.
31
31
  */
32
- export declare function requireCompletedRuntimeResponse<TResult>(responsePromise: Promise<UruAppRuntimeInvocationResponse<TResult>>): Promise<TResult>;
32
+ export declare const requireCompletedRuntimeResponse: (responsePromise: Promise<UruAppRuntimeInvocationResponse>) => Promise<unknown>;
package/dist/runtime.js CHANGED
@@ -11,47 +11,47 @@
11
11
  *
12
12
  * Imports `./errors.js` and `./types.js`, both of which import nothing back.
13
13
  */
14
- import { UruAppRuntimeError } from './errors.js';
14
+ import { UruAppRuntimeError } from "./errors.js";
15
15
  /** Drop one trailing `/` so a base URL concatenates cleanly with a rooted path. */
16
- export function trimTrailingSlash(value) {
17
- return value.endsWith('/') ? value.slice(0, -1) : value;
18
- }
16
+ export const trimTrailingSlash = (value) => value.endsWith("/") ? value.slice(0, -1) : value;
19
17
  /** Drop every leading and trailing `/` (47 is `'/'`). */
20
- function trimSlashes(value) {
18
+ const trimSlashes = (value) => {
21
19
  let start = 0;
22
20
  let end = value.length;
23
- while (start < end && value.charCodeAt(start) === 47) {
21
+ while (start < end && value.codePointAt(start) === 47) {
24
22
  start += 1;
25
23
  }
26
- while (end > start && value.charCodeAt(end - 1) === 47) {
24
+ while (end > start && value.codePointAt(end - 1) === 47) {
27
25
  end -= 1;
28
26
  }
29
27
  return start === 0 && end === value.length ? value : value.slice(start, end);
30
- }
28
+ };
31
29
  /**
32
30
  * The rooted path every runtime call hangs off, in precedence order: a public
33
31
  * page's own runtime, then the provider runtime, then an explicit override,
34
32
  * then the default in-app route.
35
33
  */
36
- export function runtimeBasePath(options) {
37
- if (options.publicPageSlug?.trim()) {
38
- return `/api/public/pages/${encodeURIComponent(options.publicPageSlug.trim())}/app-runtime`;
34
+ export const runtimeBasePath = (options) => {
35
+ const publicPageSlug = options.publicPageSlug?.trim();
36
+ if (publicPageSlug !== undefined && publicPageSlug !== "") {
37
+ return `/api/public/pages/${encodeURIComponent(publicPageSlug)}/app-runtime`;
39
38
  }
40
- if (options.providerRuntime) {
41
- return '/api/runtime/provider';
39
+ if (options.providerRuntime === true) {
40
+ return "/api/runtime/provider";
42
41
  }
43
- if (options.runtimeBasePath?.trim()) {
44
- return `/${trimSlashes(options.runtimeBasePath.trim())}`;
42
+ const explicitBasePath = options.runtimeBasePath?.trim();
43
+ if (explicitBasePath !== undefined && explicitBasePath !== "") {
44
+ return `/${trimSlashes(explicitBasePath)}`;
45
45
  }
46
- return '/api/runtime';
47
- }
46
+ return "/api/runtime";
47
+ };
48
48
  /** Resolve the caller's headers, awaiting them when they are supplied lazily. */
49
- export async function resolveHeaders(headers) {
50
- if (typeof headers === 'function') {
49
+ export const resolveHeaders = async (headers) => {
50
+ if (typeof headers === "function") {
51
51
  return await headers();
52
52
  }
53
53
  return headers;
54
- }
54
+ };
55
55
  /**
56
56
  * Narrow an invocation response to its result, or throw.
57
57
  *
@@ -59,13 +59,13 @@ export async function resolveHeaders(headers) {
59
59
  * the caller wants the value and a pending or failed call is an error rather
60
60
  * than a state to render.
61
61
  */
62
- export async function requireCompletedRuntimeResponse(responsePromise) {
62
+ export const requireCompletedRuntimeResponse = async (responsePromise) => {
63
63
  const response = await responsePromise;
64
64
  if (!response.ok || response.pending) {
65
65
  throw new UruAppRuntimeError(`Uru app runtime ${response.capabilityType} '${response.capabilityName}' did not complete successfully.`, {
66
- status: 0,
67
66
  body: response,
67
+ status: 0,
68
68
  });
69
69
  }
70
70
  return response.result;
71
- }
71
+ };
@@ -0,0 +1,9 @@
1
+ /** Opaque JSON at the HTTP edge. These are not domain model types. */
2
+ export type RuntimeJsonValue = boolean | null | number | string | RuntimeJsonValue[] | {
3
+ [key: string]: RuntimeJsonValue;
4
+ };
5
+ export type RuntimeJsonObject = Record<string, RuntimeJsonValue>;
6
+ /** Keep later JSON.stringify calls below the JavaScript stack limit. */
7
+ export declare const RUNTIME_JSON_NESTING_DEPTH_MAX = 64;
8
+ /** Validate without invoking getters or recursing on the JavaScript call stack. */
9
+ export declare const isRuntimeJsonObject: (value: unknown) => value is RuntimeJsonObject;