@funcd-dev/shim 0.23.0 → 0.25.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/build.d.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import { type Schema } from 'ts-json-schema-generator';
2
2
  export interface ContractBuild {
3
- /** an ESM module source defining the precompiled __funcdValidate* (null ⇒ no contract). */
4
- validatorSource: string | null;
5
3
  inputSchema: Schema | null;
6
4
  outputSchema: Schema | null;
7
5
  }
8
- /** Compile the FuncInput/FuncOutput contract of the TS module at `tsPath`. */
6
+ /** Build the FuncInput/FuncOutput contract of the TS module at `tsPath`; a side it does not declare is null. */
9
7
  export declare function buildContract(tsPath: string): ContractBuild;
package/dist/build.js CHANGED
@@ -1,47 +1,17 @@
1
- // funcd Node contract compiler (BUILD-TIME, ADR-0058/0060). The TS analog of funcd_build.py:
2
- // for an author module declaring `FuncInput`/`FuncOutput` types it generates the JSON Schema
3
- // (ts-json-schema-generator — closed records, no $ref) and compiles a precompiled validator
4
- // (AJV-standalone) baked into the bundle as `__funcdValidateInput`/`__funcdValidateOutput`
5
- // (`(data) => Error[]`, [] ⇒ valid) — exactly what shim.ts's resolveValidators reads.
1
+ // funcd Node contract build (BUILD-TIME, ADR-0058/0060). The TS analog of funcd_shim.build: for an
2
+ // author module declaring `FuncInput`/`FuncOutput` types it generates the JSON Schema of each side
3
+ // (ts-json-schema-generator — closed records, no $ref). It bakes no validator: funcd checks each call
4
+ // against the contract itself (funcd ADR-0303).
6
5
  //
7
- // Runs on the push box; NOT bundled into shim.mjs. The TS interfaces vanish at compile (esbuild
8
- // erases types), so unlike Python there is no source-stripping — only the validator is injected.
6
+ // Runs on the push box; NOT bundled into shim.mjs.
9
7
  //
10
8
  // (ADR-0060 names typia; typia needs a TS *transformer* (ts-patch) that does not compose with the
11
9
  // esbuild bundle. ts-json-schema-generator is the no-transformer equivalent — same "TS type ->
12
- // JSON Schema", same MIT licence; the runtime validator is still AJV-standalone as the ADR says.)
13
- import Ajv from 'ajv';
14
- import standaloneCode from 'ajv/dist/standalone/index.js';
10
+ // JSON Schema", same MIT licence.)
15
11
  import { createGenerator } from 'ts-json-schema-generator';
16
- /** Compile the FuncInput/FuncOutput contract of the TS module at `tsPath`. */
12
+ /** Build the FuncInput/FuncOutput contract of the TS module at `tsPath`; a side it does not declare is null. */
17
13
  export function buildContract(tsPath) {
18
- const inputSchema = schemaFor(tsPath, 'FuncInput');
19
- const outputSchema = schemaFor(tsPath, 'FuncOutput');
20
- if (!inputSchema && !outputSchema) {
21
- return { validatorSource: null, inputSchema: null, outputSchema: null };
22
- }
23
- // Register each schema under an $id, then standalone-code by id (the multi-export API takes
24
- // schema ids, not compiled fns). standaloneCode emits `export const _funcdInput = …` — eval-free
25
- // (compiled here, at build).
26
- // strictSchema:false ⇒ AJV ignores the `discriminator` keyword we add for the gate (it validates
27
- // a tagged union via `oneOf` alone; `discriminator` is metadata the Go profile gate requires).
28
- const ajv = new Ajv({ code: { source: true, esm: true }, allErrors: true, strictSchema: false });
29
- const refs = {};
30
- if (inputSchema) {
31
- ajv.addSchema({ ...stripMeta(inputSchema), $id: 'funcdInput' });
32
- refs._funcdInput = 'funcdInput';
33
- }
34
- if (outputSchema) {
35
- ajv.addSchema({ ...stripMeta(outputSchema), $id: 'funcdOutput' });
36
- refs._funcdOutput = 'funcdOutput';
37
- }
38
- const base = standaloneCode(ajv, refs);
39
- const wrap = (name, fn) => `export function ${name}(d) { return ${fn}(d) ? [] : (${fn}.errors ?? []); }\n`;
40
- const validatorSource = base +
41
- '\n' +
42
- (inputSchema ? wrap('__funcdValidateInput', '_funcdInput') : '') +
43
- (outputSchema ? wrap('__funcdValidateOutput', '_funcdOutput') : '');
44
- return { validatorSource, inputSchema, outputSchema };
14
+ return { inputSchema: schemaFor(tsPath, 'FuncInput'), outputSchema: schemaFor(tsPath, 'FuncOutput') };
45
15
  }
46
16
  /** Generate the JSON Schema for `type` from `tsPath`, inlined (no $ref) + closed records — the
47
17
  * funcd profile shape; returns null when the type is not declared. */
@@ -113,7 +83,7 @@ function discriminatorTag(branches) {
113
83
  }
114
84
  return null;
115
85
  }
116
- /** Drop JSON-Schema meta keys AJV/the gate don't need (the contract is the type shape). */
86
+ /** Drop JSON-Schema meta keys the gate doesn't need (the contract is the type shape). */
117
87
  function stripMeta(schema) {
118
88
  const { $schema, $ref, definitions, ...rest } = schema;
119
89
  void $schema;
package/dist/kv.d.ts CHANGED
@@ -1,14 +1,35 @@
1
- /** A function's view of its namespace-scoped KV (ADR-0069): get/put/del a binding's key, or list keys. */
1
+ /** A key's value with its version, which a compareAndSet or a delIf names. */
2
+ export interface KVEntry {
3
+ value: Uint8Array;
4
+ version: string;
5
+ }
6
+ /** How long a written key lives. Each write sets its own expiry: one without ttl leaves the key with none. */
7
+ export interface PutOptions {
8
+ /** Whole seconds from 1: the key lives at least ttl from when funcd takes the write, so a holder that counts its
9
+ * lease from before the call never counts past the key's expiry. Renew it with a compareAndSet and a new ttl. */
10
+ ttl?: number;
11
+ }
12
+ /** A function's view of its namespace-scoped KV (ADR-0069): get/put/del a binding's key, or list keys.
13
+ * putIfAbsent, compareAndSet and delIf write only while their condition holds and say who won: of racing writers
14
+ * exactly one gets the new version, the others null (false for a delete). */
2
15
  export interface KVClient {
3
16
  get(binding: string, key: string): Promise<Uint8Array | null>;
17
+ /** get() with the key's version (a missing key is null). */
18
+ getEntry(binding: string, key: string): Promise<KVEntry | null>;
4
19
  /** get() decoded as UTF-8 text — the common case (a missing key is null). Saves the caller a
5
20
  * TextDecoder dance; put() already accepts a string. */
6
21
  getText(binding: string, key: string): Promise<string | null>;
7
22
  /** get() decoded as UTF-8 text then JSON-parsed (a missing key is null). The structured-value
8
23
  * counterpart of getText; write with put(binding, key, JSON.stringify(value)). */
9
24
  getJSON<T = unknown>(binding: string, key: string): Promise<T | null>;
10
- put(binding: string, key: string, value: Uint8Array | string): Promise<void>;
25
+ put(binding: string, key: string, value: Uint8Array | string, opts?: PutOptions): Promise<void>;
26
+ /** Create the key: its new version, or null when it exists (an expired key does not). */
27
+ putIfAbsent(binding: string, key: string, value: Uint8Array | string, opts?: PutOptions): Promise<string | null>;
28
+ /** Replace the key while it is at version: its new version, or null when it is not. */
29
+ compareAndSet(binding: string, key: string, value: Uint8Array | string, version: string, opts?: PutOptions): Promise<string | null>;
11
30
  del(binding: string, key: string): Promise<void>;
31
+ /** Delete the key while it is at version, as a lease holder releases what it holds. */
32
+ delIf(binding: string, key: string, version: string): Promise<boolean>;
12
33
  list(binding: string, prefix?: string): Promise<string[]>;
13
34
  }
14
35
  /** Build the context.kv client. In a pool, `member` names the calling function on every request
package/dist/kv.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // same per-sandbox socket as context.invoke (FUNCD_INVOKE_SOCKET); the platform routes /kv/… to the
3
3
  // PDP-authorized Facade with the sandbox's namespace identity. Reached only through the built-in shim.
4
4
  import { send as sendOn } from "./socket.js";
5
- const send = (method, path, body, member) => sendOn('context.kv', method, path, body, member);
5
+ const send = (method, path, body, member, headers) => sendOn('context.kv', method, path, body, member, undefined, headers);
6
6
  const enc = encodeURIComponent;
7
7
  // key may be hierarchical ("a/b"); keep the "/" separators (the server's {key...} captures them), encode segments.
8
8
  const keyPath = (binding, key) => `/kv/${enc(binding)}/${key.split('/').map(enc).join('/')}`;
@@ -18,10 +18,28 @@ const json = (verb, r, text) => {
18
18
  });
19
19
  }
20
20
  };
21
+ const version = (r) => (r.etag ?? '').replace(/^"|"$/g, '');
22
+ const withTTL = (path, opts) => {
23
+ if (opts?.ttl === undefined)
24
+ return path;
25
+ if (!Number.isSafeInteger(opts.ttl) || opts.ttl < 1) {
26
+ throw new RangeError(`context.kv: ttl must be a whole number of seconds from 1, not ${opts.ttl}`);
27
+ }
28
+ return `${path}?ttl=${opts.ttl}`;
29
+ };
30
+ const bytes = (value) => typeof value === 'string' ? Buffer.from(value, 'utf8') : Buffer.from(value);
21
31
  /** Build the context.kv client. In a pool, `member` names the calling function on every request
22
32
  * (funcd checks it against the pool's members); the solo shim passes none. */
23
33
  export function makeKV(member) {
24
- const request = (method, path, body) => send(method, path, body, member);
34
+ const request = (method, path, body, headers) => send(method, path, body, member, headers);
35
+ const conditionalPut = async (verb, binding, key, value, opts, headers) => {
36
+ const r = await request('PUT', withTTL(keyPath(binding, key), opts), bytes(value), headers);
37
+ if (r.status === 412)
38
+ return null;
39
+ if (!ok(r))
40
+ throw fail(verb, r);
41
+ return version(r);
42
+ };
25
43
  return {
26
44
  async get(binding, key) {
27
45
  const r = await request('GET', keyPath(binding, key));
@@ -31,6 +49,14 @@ export function makeKV(member) {
31
49
  throw fail('get', r);
32
50
  return new Uint8Array(r.body);
33
51
  },
52
+ async getEntry(binding, key) {
53
+ const r = await request('GET', keyPath(binding, key));
54
+ if (r.status === 404)
55
+ return null;
56
+ if (!ok(r))
57
+ throw fail('getEntry', r);
58
+ return { value: new Uint8Array(r.body), version: version(r) };
59
+ },
34
60
  async getText(binding, key) {
35
61
  const r = await request('GET', keyPath(binding, key));
36
62
  if (r.status === 404)
@@ -47,17 +73,30 @@ export function makeKV(member) {
47
73
  throw fail('get', r);
48
74
  return json('getJSON', r, r.body.toString('utf8'));
49
75
  },
50
- async put(binding, key, value) {
51
- const buf = typeof value === 'string' ? Buffer.from(value, 'utf8') : Buffer.from(value);
52
- const r = await request('PUT', keyPath(binding, key), buf);
76
+ async put(binding, key, value, opts) {
77
+ const r = await request('PUT', withTTL(keyPath(binding, key), opts), bytes(value));
53
78
  if (!ok(r))
54
79
  throw fail('put', r);
55
80
  },
81
+ putIfAbsent(binding, key, value, opts) {
82
+ return conditionalPut('putIfAbsent', binding, key, value, opts, { 'if-none-match': '*' });
83
+ },
84
+ compareAndSet(binding, key, value, v, opts) {
85
+ return conditionalPut('compareAndSet', binding, key, value, opts, { 'if-match': `"${v}"` });
86
+ },
56
87
  async del(binding, key) {
57
88
  const r = await request('DELETE', keyPath(binding, key));
58
89
  if (!ok(r))
59
90
  throw fail('del', r);
60
91
  },
92
+ async delIf(binding, key, v) {
93
+ const r = await request('DELETE', keyPath(binding, key), undefined, { 'if-match': `"${v}"` });
94
+ if (r.status === 412)
95
+ return false;
96
+ if (!ok(r))
97
+ throw fail('delIf', r);
98
+ return true;
99
+ },
61
100
  async list(binding, prefix) {
62
101
  const q = prefix ? `?prefix=${enc(prefix)}` : '';
63
102
  const r = await request('GET', `/kv/${enc(binding)}${q}`);
package/dist/socket.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export interface Resp {
2
2
  status: number;
3
3
  body: Buffer;
4
+ /** The reply's ETag, when it has one: a KV key's version. */
5
+ etag?: string;
4
6
  }
5
- /** send makes one request; `client` names the context client in its errors ("context.kv"). */
6
- export declare function send(client: string, method: string, path: string, body: Buffer | undefined, member: string | undefined, contentType?: string): Promise<Resp>;
7
+ /** send makes one request with `extra` headers; `client` names the context client in its errors ("context.kv"). */
8
+ export declare function send(client: string, method: string, path: string, body: Buffer | undefined, member: string | undefined, contentType?: string, extra?: Record<string, string>): Promise<Resp>;
package/dist/socket.js CHANGED
@@ -2,8 +2,8 @@
2
2
  // per-sandbox socket (FUNCD_INVOKE_SOCKET), as the calling pool member when one is given.
3
3
  import http from 'node:http';
4
4
  import { MEMBER_HEADER } from "./invoke.js";
5
- /** send makes one request; `client` names the context client in its errors ("context.kv"). */
6
- export function send(client, method, path, body, member, contentType) {
5
+ /** send makes one request with `extra` headers; `client` names the context client in its errors ("context.kv"). */
6
+ export function send(client, method, path, body, member, contentType, extra) {
7
7
  return new Promise((resolve, reject) => {
8
8
  const socketPath = process.env.FUNCD_INVOKE_SOCKET;
9
9
  if (!socketPath) {
@@ -17,12 +17,13 @@ export function send(client, method, path, body, member, contentType) {
17
17
  headers['content-type'] = contentType;
18
18
  if (member)
19
19
  headers[MEMBER_HEADER] = member;
20
+ Object.assign(headers, extra);
20
21
  const req = http.request({ socketPath, path, method, headers }, (res) => {
21
22
  const chunks = [];
22
23
  // A connection that drops mid-body errors the response, not the request, and never ends it.
23
24
  res.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: connection closed before the reply ended`, { cause: err })));
24
25
  res.on('data', (c) => chunks.push(c));
25
- res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks) }));
26
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks), etag: res.headers.etag }));
26
27
  });
27
28
  req.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: ${err.message}`, { cause: err })));
28
29
  if (body)
package/dist/types.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { SQLClient } from './sql.ts';
4
4
  import type { ConfigClient } from './config.ts';
5
5
  import type { SecretClient } from './secret.ts';
6
6
  import type { LakeClient } from './lake.ts';
7
- export type { KVClient } from './kv.ts';
7
+ export type { KVClient, KVEntry, PutOptions } from './kv.ts';
8
8
  export type { BlobClient, SignOptions } from './blob.ts';
9
9
  export type { SQLClient, SQLExecResult, SQLParam, SQLParams, SQLRow, SQLStatement, SQLValues, } from './sql.ts';
10
10
  export type { ConfigClient } from './config.ts';
@@ -27,9 +27,9 @@ export interface CloudEvent<T = unknown> {
27
27
  export interface FunctionContext {
28
28
  /** Structured log line → stdout (collected by the platform, ADR-0010). */
29
29
  log(...args: unknown[]): void;
30
- /** Synchronously invoke a linked function by its spec.bindings.links alias (ADR-0064). The input is
31
- * validated against the target's contract by the target's shim; its result is returned. Fails
32
- * closed (rejects) if the caller declares no such link.
30
+ /** Synchronously invoke a linked function by its spec.bindings.links alias (ADR-0064). funcd checks the
31
+ * input against the target's contract (funcd ADR-0303); its result is returned. Fails closed (rejects) if
32
+ * the caller declares no such link.
33
33
  *
34
34
  * The target receives `input` as its `event.data`, except that an object with a top-level `data` or
35
35
  * `specversion` key is taken as a full CloudEvent envelope (ADR-0134): the target receives only its
@@ -81,10 +81,3 @@ export declare function http(app: HttpApp): HttpHandler;
81
81
  * generated contract is the empty schema `{}` (accepts any JSON). Typed as `unknown` so the
82
82
  * handler must narrow before use — deliberately NOT the unsafe `any`. */
83
83
  export type Json = unknown;
84
- /** A single error from a precompiled validator. Shape kept loose (AJV vs pydantic differ); the
85
- * shim only inspects the array length and echoes the errors as 422/500 details. */
86
- export type ValidationError = unknown;
87
- /** A precompiled, eval-free validator the push build inlines into the bundle from the author's
88
- * FuncInput/FuncOutput type (ADR-0058). Returns [] when `data` is valid. The shim runs it; it
89
- * never compiles a schema at runtime. */
90
- export type Validator = (data: unknown) => ValidationError[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funcd-dev/shim",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "type": "module",
5
5
  "description": "Types and the contract build for writing funcd functions in TypeScript",
6
6
  "license": "Apache-2.0",
@@ -38,8 +38,6 @@
38
38
  "build:lib": "tsc -p tsconfig.lib.json"
39
39
  },
40
40
  "dependencies": {
41
- "ajv": "^8.20.0",
42
- "ajv-formats": "^3.0.1",
43
41
  "ts-json-schema-generator": "^2.9.0"
44
42
  },
45
43
  "devDependencies": {