@glassbox-ai/engine 0.0.0-stage → 0.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.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +31 -2
  3. package/dist/action/acc.d.ts +48 -0
  4. package/dist/action/acc.js +117 -0
  5. package/dist/action/inline.d.ts +14 -0
  6. package/dist/action/inline.js +54 -0
  7. package/dist/action/paths.d.ts +71 -0
  8. package/dist/action/paths.js +398 -0
  9. package/dist/action/powershell.d.ts +9 -0
  10. package/dist/action/powershell.js +848 -0
  11. package/dist/action/protected-write.d.ts +11 -0
  12. package/dist/action/protected-write.js +113 -0
  13. package/dist/action/schedule.d.ts +43 -0
  14. package/dist/action/schedule.js +213 -0
  15. package/dist/action/shell/analyze.d.ts +28 -0
  16. package/dist/action/shell/analyze.js +2030 -0
  17. package/dist/action/shell/parse.d.ts +74 -0
  18. package/dist/action/shell/parse.js +1037 -0
  19. package/dist/action/shell/view.d.ts +6 -0
  20. package/dist/action/shell/view.js +89 -0
  21. package/dist/action/sql.d.ts +3 -0
  22. package/dist/action/sql.js +259 -0
  23. package/dist/action/tools.d.ts +20 -0
  24. package/dist/action/tools.js +240 -0
  25. package/dist/action/upload.d.ts +17 -0
  26. package/dist/action/upload.js +72 -0
  27. package/dist/analysis/fields.d.ts +14 -0
  28. package/dist/analysis/fields.js +136 -0
  29. package/dist/analysis/findings.d.ts +25 -0
  30. package/dist/analysis/findings.js +82 -0
  31. package/dist/analysis/gate.d.ts +16 -0
  32. package/dist/analysis/gate.js +660 -0
  33. package/dist/analysis/manifest.d.ts +3 -0
  34. package/dist/analysis/manifest.js +369 -0
  35. package/dist/analysis/match.d.ts +54 -0
  36. package/dist/analysis/match.js +352 -0
  37. package/dist/analysis/scan.d.ts +17 -0
  38. package/dist/analysis/scan.js +97 -0
  39. package/dist/canon/confusables.generated.d.ts +3 -0
  40. package/dist/canon/confusables.generated.js +6 -0
  41. package/dist/canon/decode.d.ts +11 -0
  42. package/dist/canon/decode.js +147 -0
  43. package/dist/canon/views.d.ts +36 -0
  44. package/dist/canon/views.js +283 -0
  45. package/dist/evidence/evidence.d.ts +12 -0
  46. package/dist/evidence/evidence.js +149 -0
  47. package/dist/fingerprint/diff.d.ts +3 -0
  48. package/dist/fingerprint/diff.js +273 -0
  49. package/dist/fingerprint/fingerprint.d.ts +4 -0
  50. package/dist/fingerprint/fingerprint.js +77 -0
  51. package/dist/grade/score.d.ts +19 -0
  52. package/dist/grade/score.js +89 -0
  53. package/dist/index.d.ts +22 -0
  54. package/dist/index.js +148 -0
  55. package/dist/intake/json.d.ts +17 -0
  56. package/dist/intake/json.js +284 -0
  57. package/dist/intake/snapshot.d.ts +14 -0
  58. package/dist/intake/snapshot.js +130 -0
  59. package/dist/limits.d.ts +4 -0
  60. package/dist/limits.js +30 -0
  61. package/dist/policy/decide.d.ts +26 -0
  62. package/dist/policy/decide.js +74 -0
  63. package/dist/rules/ids.d.ts +2 -0
  64. package/dist/rules/ids.js +99 -0
  65. package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
  66. package/dist/ruleset/baseline-tests.generated.js +2935 -0
  67. package/dist/ruleset/baseline.d.ts +3 -0
  68. package/dist/ruleset/baseline.generated.d.ts +3 -0
  69. package/dist/ruleset/baseline.generated.js +5 -0
  70. package/dist/ruleset/baseline.js +44 -0
  71. package/dist/ruleset/fakes.d.ts +3 -0
  72. package/dist/ruleset/fakes.js +26 -0
  73. package/dist/ruleset/load.d.ts +14 -0
  74. package/dist/ruleset/load.js +173 -0
  75. package/dist/ruleset/schema.d.ts +120 -0
  76. package/dist/ruleset/schema.js +54 -0
  77. package/dist/ruleset/selftest.d.ts +18 -0
  78. package/dist/ruleset/selftest.js +42 -0
  79. package/dist/ruleset-entry.d.ts +5 -0
  80. package/dist/ruleset-entry.js +7 -0
  81. package/dist/secrets/detect.d.ts +17 -0
  82. package/dist/secrets/detect.js +236 -0
  83. package/dist/secrets/redact.d.ts +19 -0
  84. package/dist/secrets/redact.js +116 -0
  85. package/dist/types.d.ts +434 -0
  86. package/dist/types.js +10 -0
  87. package/dist/util/hash.d.ts +4 -0
  88. package/dist/util/hash.js +16 -0
  89. package/dist/util/initclock.d.ts +3 -0
  90. package/dist/util/initclock.js +17 -0
  91. package/dist/util/jcs.d.ts +4 -0
  92. package/dist/util/jcs.js +91 -0
  93. package/dist/util/misc.d.ts +17 -0
  94. package/dist/util/misc.js +77 -0
  95. package/dist/util/re.d.ts +14 -0
  96. package/dist/util/re.js +47 -0
  97. package/dist/version.d.ts +2 -0
  98. package/dist/version.js +2 -0
  99. package/package.json +55 -3
@@ -0,0 +1,434 @@
1
+ export type Verdict = "allow" | "warn" | "ask" | "deny";
2
+ export type Severity = "info" | "low" | "medium" | "high" | "critical";
3
+ export type ActionRiskLevel = "read" | "write-reversible" | "high-risk";
4
+ export type ApprovalMode = "autopilot" | "balanced" | "strict";
5
+ export type Grade = "A" | "B" | "C" | "D" | "F";
6
+ export type Category = "tool-poisoning" | "hidden-content" | "prompt-injection" | "shadowing" | "rug-pull" | "exfiltration" | "secret-exposure" | "dangerous-action" | "obfuscation" | "capability-mismatch" | "self-protection" | "integrity" | "resource-limit" | "hygiene" | "server-request" | "toxic-flow";
7
+ export declare const ACTION_TAGS: readonly ["fs.read", "fs.read.sensitive", "fs.write", "fs.delete", "fs.destroy", "fs.move", "net.egress", "net.fetch.package-manager", "net.fetch.vcs", "vcs.commit", "vcs.push", "vcs.force-push", "vcs.history-rewrite", "vcs.discard-changes", "db.read", "db.write", "db.delete", "db.ddl", "db.unscoped-write", "deploy.prod", "deploy.other", "infra.change", "payment", "publish.public", "message.send", "perm.change", "exec.inline-code", "exec.project-code", "exec.unknown", "exec.nested-agent", "config.agent", "self-protection"];
8
+ export type ActionTag = (typeof ACTION_TAGS)[number];
9
+ export type ViaKind = "base64" | "hex" | "url" | "tag-chars" | "concat" | "skeleton" | "invisible-stripped";
10
+ export interface Finding {
11
+ id: string;
12
+ ruleId: string;
13
+ ruleSource: "baseline" | "private";
14
+ category: Category;
15
+ severity: Severity;
16
+ confidence: number;
17
+ location: string;
18
+ span?: {
19
+ start: number;
20
+ end: number;
21
+ };
22
+ via?: readonly ViaKind[];
23
+ related?: readonly string[];
24
+ evidence: string;
25
+ explanation: string;
26
+ remediation: string;
27
+ }
28
+ export interface ActionRisk {
29
+ level: ActionRiskLevel;
30
+ tags: readonly ActionTag[];
31
+ unanalyzable: boolean;
32
+ selfProtection: boolean;
33
+ reasons: readonly string[];
34
+ }
35
+ export type SessionSignal = {
36
+ kind: "sensitive-read";
37
+ label: string;
38
+ atCall: number;
39
+ } | {
40
+ kind: "injection-seen";
41
+ serverId: string;
42
+ mentionedTools: readonly string[];
43
+ atCall: number;
44
+ } | {
45
+ kind: "secret-seen";
46
+ secretType: string;
47
+ atCall: number;
48
+ } | {
49
+ kind: "private-data-read";
50
+ source: string;
51
+ serverId: string;
52
+ toolName: string;
53
+ atCall: number;
54
+ } | {
55
+ kind: "untrusted-content-seen";
56
+ serverId: string;
57
+ toolName: string;
58
+ atCall: number;
59
+ } | {
60
+ kind: "external-write";
61
+ serverId: string;
62
+ toolName: string;
63
+ tags: readonly ActionTag[];
64
+ atCall: number;
65
+ } | {
66
+ kind: "protection-degraded";
67
+ reason: "tampered" | "downgrade" | "internal-error";
68
+ atCall: number;
69
+ }
70
+ /**
71
+ * A scheduled job created or changed by this call, and the files it runs (rev 9). Keep it only
72
+ * if the call was approved and ran; it doesn't expire. Later edits of these files ask (CP-SELF-007).
73
+ */
74
+ | {
75
+ kind: "scheduled-job";
76
+ job: "cron" | "systemd" | "at" | "launchd" | "autostart" | "startup-folder" | "task-scheduler" | "service" | "boot-script";
77
+ schedule: string | null;
78
+ files: readonly string[];
79
+ atCall: number;
80
+ };
81
+ export interface Decision {
82
+ verdict: Verdict;
83
+ actionRisk: ActionRisk;
84
+ findings: readonly Finding[];
85
+ rulesetVersion: string;
86
+ engineVersion: string;
87
+ degraded: boolean;
88
+ degradedReasons: readonly string[];
89
+ protectionDegraded: boolean;
90
+ signals: readonly SessionSignal[];
91
+ suppressed: readonly {
92
+ ruleId: string;
93
+ count: number;
94
+ }[];
95
+ mode: ApprovalMode;
96
+ verdictBeforeMode?: Verdict;
97
+ inputDigest: string;
98
+ resultRewrite?: {
99
+ kind: "redact-secrets" | "replace-with-notice";
100
+ value: unknown;
101
+ };
102
+ elapsedMs: number;
103
+ }
104
+ export interface ToolDef {
105
+ name: string;
106
+ title?: string;
107
+ description?: string;
108
+ inputSchema?: unknown;
109
+ outputSchema?: unknown;
110
+ annotations?: {
111
+ title?: string;
112
+ readOnlyHint?: boolean;
113
+ destructiveHint?: boolean;
114
+ idempotentHint?: boolean;
115
+ openWorldHint?: boolean;
116
+ [k: string]: unknown;
117
+ };
118
+ [k: string]: unknown;
119
+ }
120
+ export interface ServerManifest {
121
+ serverId?: string;
122
+ initialize?: {
123
+ protocolVersion?: string;
124
+ serverInfo?: {
125
+ name?: string;
126
+ version?: string;
127
+ title?: string;
128
+ [k: string]: unknown;
129
+ };
130
+ capabilities?: Record<string, unknown>;
131
+ instructions?: string;
132
+ [k: string]: unknown;
133
+ };
134
+ tools?: readonly ToolDef[];
135
+ prompts?: readonly Record<string, unknown>[];
136
+ resources?: readonly Record<string, unknown>[];
137
+ resourceTemplates?: readonly Record<string, unknown>[];
138
+ [k: string]: unknown;
139
+ }
140
+ export interface Limits {
141
+ maxInputBytes: number;
142
+ maxDepth: number;
143
+ maxNodes: number;
144
+ maxTools: number;
145
+ maxDescriptionBytes: number;
146
+ maxFieldScanBytes: number;
147
+ maxCommandBytes: number;
148
+ maxSqlBytes: number;
149
+ maxDecodeDepth: number;
150
+ maxDecodedBytes: number;
151
+ maxFindings: number;
152
+ maxStringBytes: number;
153
+ timeBudgetMs: number;
154
+ hardStopMs: number;
155
+ signalTtlCalls: number;
156
+ minConfidenceForVerdict: number;
157
+ }
158
+ export interface AnalyzeOptions {
159
+ knownTools?: readonly {
160
+ serverId: string;
161
+ name: string;
162
+ }[];
163
+ limits?: Partial<Limits>;
164
+ ruleset?: LoadedRuleset;
165
+ evidenceMode?: "snippet" | "none";
166
+ sessionIdShape?: ServerReport["sessionIdShape"];
167
+ }
168
+ export interface ServerReport {
169
+ grade: Grade;
170
+ score: number;
171
+ partial: boolean;
172
+ caps: readonly {
173
+ cap: Grade;
174
+ reason: string;
175
+ findingIds: readonly string[];
176
+ }[];
177
+ deductions: readonly {
178
+ findingId: string;
179
+ points: number;
180
+ }[];
181
+ findings: readonly Finding[];
182
+ capabilityProfile: readonly {
183
+ tool: string;
184
+ risk: ActionRisk;
185
+ }[];
186
+ scope: "metadata-only";
187
+ sessionIdShape?: {
188
+ length: number;
189
+ charset: "hex" | "base64" | "alnum" | "digits" | "other";
190
+ sequentialSuspected: boolean;
191
+ };
192
+ fingerprint: Fingerprint;
193
+ rulesetVersion: string;
194
+ engineVersion: string;
195
+ degraded: boolean;
196
+ degradedReasons: readonly string[];
197
+ elapsedMs: number;
198
+ }
199
+ export interface ToolCallInput {
200
+ serverId: string;
201
+ toolName: string;
202
+ arguments: unknown;
203
+ descriptor?: ToolDef;
204
+ agent?: string;
205
+ }
206
+ export interface ToolResultInput {
207
+ call: ToolCallInput;
208
+ result: unknown;
209
+ isError?: boolean;
210
+ }
211
+ export type ServerRequestKind = "sampling" | "elicitation" | "roots" | "ping" | "notification" | "unknown";
212
+ export interface ServerRequestInput {
213
+ serverId: string;
214
+ message: unknown;
215
+ }
216
+ export interface RememberedRule {
217
+ projectIdHash: string;
218
+ serverId: string;
219
+ toolName: string;
220
+ actionTag: ActionTag;
221
+ createdAt: string;
222
+ }
223
+ export type PolicyChoice = "allow" | "ask" | "deny";
224
+ export interface UserPolicy {
225
+ mode: ApprovalMode;
226
+ tagOverrides?: Partial<Record<ActionTag, PolicyChoice>>;
227
+ disabledRules?: readonly string[];
228
+ extraProtectedPaths?: readonly string[];
229
+ extraSensitivePaths?: readonly string[];
230
+ serverRequests?: {
231
+ default?: Partial<Record<ServerRequestKind, PolicyChoice>>;
232
+ perServer?: Readonly<Record<string, Partial<Record<ServerRequestKind, PolicyChoice>>>>;
233
+ };
234
+ }
235
+ export interface SessionContext {
236
+ sessionId: string;
237
+ platform: "linux" | "darwin" | "win32";
238
+ claudeConfigDir?: string;
239
+ glassboxSecretPaths?: readonly string[];
240
+ remembered?: readonly RememberedRule[];
241
+ homeDir: string;
242
+ cwd: string;
243
+ caseInsensitiveFs: boolean;
244
+ glassboxDirs: readonly string[];
245
+ resolvedPaths?: Readonly<Record<string, string>>;
246
+ servers: readonly {
247
+ serverId: string;
248
+ toolNames: readonly string[];
249
+ highRiskTools?: readonly string[];
250
+ identity?: {
251
+ host?: string;
252
+ issuerTags?: readonly string[];
253
+ };
254
+ }[];
255
+ signals?: readonly SessionSignal[];
256
+ policy: UserPolicy;
257
+ ruleset: LoadedRuleset;
258
+ limits?: Partial<Limits>;
259
+ evidenceMode?: "snippet" | "none";
260
+ }
261
+ export interface ActionContext {
262
+ platform?: SessionContext["platform"];
263
+ homeDir?: string;
264
+ cwd?: string;
265
+ caseInsensitiveFs?: boolean;
266
+ glassboxDirs?: readonly string[];
267
+ }
268
+ export interface ItemFingerprint {
269
+ name: string;
270
+ hash: string;
271
+ }
272
+ export interface ToolFingerprint {
273
+ name: string;
274
+ hash: string;
275
+ parts: {
276
+ title: string;
277
+ description: string;
278
+ inputSchema: string;
279
+ outputSchema: string;
280
+ annotations: string;
281
+ };
282
+ snapshot: {
283
+ description: string;
284
+ inputSchema: unknown;
285
+ annotations: unknown;
286
+ title: string;
287
+ };
288
+ }
289
+ export interface Fingerprint {
290
+ algorithm: "glassbox-fp-v1";
291
+ manifest: string;
292
+ server: {
293
+ instructions: string | null;
294
+ serverInfo: string | null;
295
+ };
296
+ serverSnapshot: {
297
+ name: string | null;
298
+ title: string | null;
299
+ version: string | null;
300
+ };
301
+ tools: readonly ToolFingerprint[];
302
+ prompts: readonly ItemFingerprint[];
303
+ resources: readonly ItemFingerprint[];
304
+ resourceTemplates: readonly ItemFingerprint[];
305
+ truncated: boolean;
306
+ }
307
+ export type FingerprintResult = {
308
+ ok: true;
309
+ fingerprint: Fingerprint;
310
+ findings: readonly Finding[];
311
+ } | {
312
+ ok: false;
313
+ findings: readonly Finding[];
314
+ degraded: true;
315
+ };
316
+ export type ChangeKind = "tool-added" | "tool-removed" | "description-changed" | "title-changed" | "schema-widened" | "schema-narrowed" | "schema-changed-indeterminate" | "annotations-escalated" | "annotations-changed" | "server-instructions-changed" | "serverinfo-changed" | "prompt-added" | "resource-added" | "output-schema-changed" | "fingerprint-incomparable";
317
+ export interface ManifestChange {
318
+ kind: ChangeKind;
319
+ item: string;
320
+ pointer: string;
321
+ detail: string;
322
+ }
323
+ export interface ManifestDiff {
324
+ changed: boolean;
325
+ changes: readonly ManifestChange[];
326
+ findings: readonly Finding[];
327
+ degraded: boolean;
328
+ }
329
+ export interface DiffOptions {
330
+ baseline?: "approved" | "public-grade";
331
+ }
332
+ export interface RedactOptions {
333
+ evidenceMode?: "snippet" | "none";
334
+ limits?: Partial<Limits>;
335
+ }
336
+ export interface Redacted {
337
+ value: unknown;
338
+ redactions: readonly {
339
+ pointer: string;
340
+ type: string;
341
+ masked: string;
342
+ }[];
343
+ truncated: boolean;
344
+ }
345
+ export type ViewName = "norm" | "skeleton" | "visible" | "original" | "tagDecoded" | "decoded";
346
+ export type Surface = "manifest" | "call" | "result" | "server-request";
347
+ export type Matcher = {
348
+ type: "phrase";
349
+ phrases: readonly string[];
350
+ wordBoundary: boolean;
351
+ maxGapWords?: number;
352
+ }
353
+ /**
354
+ * `anchors` (spec rev 6): literals of which every match contains at least one, compared
355
+ * against the lowercased text. When none occurs, the regex pass is skipped. Anchors are
356
+ * lowercase; non-ASCII anchors are only allowed without the `i` flag (re2's case folding and
357
+ * toLowerCase differ outside ASCII). Baseline anchors are proven by test/ruleset/anchors.test.
358
+ */
359
+ | {
360
+ type: "regex";
361
+ pattern: string;
362
+ flags?: "i";
363
+ anchors?: readonly string[];
364
+ } | {
365
+ type: "codepoints";
366
+ ranges: readonly (readonly [number, number])[];
367
+ minCount: number;
368
+ exclude?: "emoji-sequences";
369
+ } | {
370
+ type: "secret";
371
+ detector: string;
372
+ } | {
373
+ type: "structural";
374
+ check: string;
375
+ } | {
376
+ type: "all" | "any";
377
+ of: readonly Matcher[];
378
+ scope: "field";
379
+ } | {
380
+ type: "not";
381
+ of: Matcher;
382
+ };
383
+ export interface RuleTestCase {
384
+ surface: Surface;
385
+ input: unknown;
386
+ note?: string;
387
+ }
388
+ export interface RuleDef {
389
+ id: string;
390
+ revision: number;
391
+ category: Category;
392
+ severity: Severity;
393
+ confidence: number;
394
+ surfaces: readonly Surface[];
395
+ target: {
396
+ roles?: readonly string[];
397
+ keys?: boolean;
398
+ };
399
+ views: readonly ViewName[];
400
+ matcher: Matcher;
401
+ escalation?: boolean;
402
+ suppressible: boolean;
403
+ explanation: string;
404
+ remediation: string;
405
+ testCases: {
406
+ positive: readonly RuleTestCase[];
407
+ negative: readonly RuleTestCase[];
408
+ };
409
+ }
410
+ export interface LoadedRuleset {
411
+ status: "ok" | "loaded-with-errors" | "fallback" | "unavailable";
412
+ rulesetId: string;
413
+ version: string;
414
+ sequence: number;
415
+ expiresAt: string;
416
+ /** "now" passed to loadRuleset; used only to compute `expired`. */
417
+ expired: boolean;
418
+ protectionDegraded: boolean;
419
+ degradedCause?: "tampered" | "downgrade";
420
+ rules: readonly RuleDef[];
421
+ irreversibleTags: readonly ActionTag[];
422
+ errors: readonly string[];
423
+ }
424
+ export interface TrustedKey {
425
+ keyId: string;
426
+ publicKey: Uint8Array;
427
+ }
428
+ export interface LoadRulesetOptions {
429
+ minSequence: number;
430
+ now: string;
431
+ /** Test/dev only. Production callers must not pass this; the embedded keys apply. */
432
+ trustedKeys?: readonly TrustedKey[];
433
+ }
434
+ //# sourceMappingURL=types.d.ts.map
package/dist/types.js ADDED
@@ -0,0 +1,10 @@
1
+ // Public types (engine-spec §4). Kept free of logic.
2
+ export const ACTION_TAGS = [
3
+ "fs.read", "fs.read.sensitive", "fs.write", "fs.delete", "fs.destroy", "fs.move", "net.egress",
4
+ "net.fetch.package-manager", "net.fetch.vcs", "vcs.commit", "vcs.push", "vcs.force-push",
5
+ "vcs.history-rewrite", "vcs.discard-changes", "db.read", "db.write", "db.delete", "db.ddl",
6
+ "db.unscoped-write", "deploy.prod", "deploy.other", "infra.change", "payment", "publish.public",
7
+ "message.send", "perm.change", "exec.inline-code", "exec.project-code", "exec.unknown",
8
+ "exec.nested-agent", "config.agent", "self-protection",
9
+ ];
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,4 @@
1
+ export declare function utf8(s: string): Uint8Array;
2
+ export declare function toHex(bytes: Uint8Array): string;
3
+ export declare function sha256Hex(s: string | Uint8Array): string;
4
+ //# sourceMappingURL=hash.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ const encoder = new TextEncoder();
3
+ const HEX = "0123456789abcdef";
4
+ export function utf8(s) {
5
+ return encoder.encode(s);
6
+ }
7
+ export function toHex(bytes) {
8
+ let out = "";
9
+ for (const b of bytes)
10
+ out += HEX[b >> 4] + HEX[b & 15];
11
+ return out;
12
+ }
13
+ export function sha256Hex(s) {
14
+ return toHex(sha256(typeof s === "string" ? utf8(s) : s));
15
+ }
16
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1,3 @@
1
+ export declare function initTimed<T>(fn: () => T): T;
2
+ export declare function initMs(): number;
3
+ //# sourceMappingURL=initclock.d.ts.map
@@ -0,0 +1,17 @@
1
+ // Time spent on one-time initialization (compiling linear regexes, building lookup tables).
2
+ // The per-call hardStopMs backstop excludes it, so a cold first call isn't mistaken for a
3
+ // pathological input. Pure bookkeeping: it never changes a result.
4
+ let total = 0;
5
+ export function initTimed(fn) {
6
+ const t = performance.now();
7
+ try {
8
+ return fn();
9
+ }
10
+ finally {
11
+ total += performance.now() - t;
12
+ }
13
+ }
14
+ export function initMs() {
15
+ return total;
16
+ }
17
+ //# sourceMappingURL=initclock.js.map
@@ -0,0 +1,4 @@
1
+ export declare class JcsError extends Error {
2
+ }
3
+ export declare function jcs(value: unknown): string;
4
+ //# sourceMappingURL=jcs.d.ts.map
@@ -0,0 +1,91 @@
1
+ // RFC 8785 JSON Canonicalization Scheme, hand-written (engine-spec §12.8).
2
+ // Works on snapshot values (null-prototype objects, arrays, strings, finite numbers,
3
+ // booleans, null). Iterative, so input depth can't overflow the stack.
4
+ export class JcsError extends Error {
5
+ }
6
+ function serializeString(s) {
7
+ let out = '"';
8
+ for (let i = 0; i < s.length; i++) {
9
+ const c = s.charCodeAt(i);
10
+ if (c === 0x22)
11
+ out += '\\"';
12
+ else if (c === 0x5c)
13
+ out += "\\\\";
14
+ else if (c === 0x08)
15
+ out += "\\b";
16
+ else if (c === 0x0c)
17
+ out += "\\f";
18
+ else if (c === 0x0a)
19
+ out += "\\n";
20
+ else if (c === 0x0d)
21
+ out += "\\r";
22
+ else if (c === 0x09)
23
+ out += "\\t";
24
+ else if (c < 0x20)
25
+ out += "\\u" + c.toString(16).padStart(4, "0");
26
+ else
27
+ out += s[i];
28
+ }
29
+ return out + '"';
30
+ }
31
+ function serializeNumber(n) {
32
+ if (!Number.isFinite(n))
33
+ throw new JcsError("non-finite number");
34
+ // ECMAScript Number::toString is exactly the RFC 8785 number format.
35
+ return Object.is(n, -0) ? "0" : String(n);
36
+ }
37
+ /** Compare by UTF-16 code units, as RFC 8785 §3.2.3 requires. */
38
+ function compareKeys(a, b) {
39
+ return a < b ? -1 : a > b ? 1 : 0;
40
+ }
41
+ export function jcs(value) {
42
+ const parts = [];
43
+ const stack = [{ kind: "value", v: value }];
44
+ let steps = 0;
45
+ while (stack.length > 0) {
46
+ if (++steps > 5_000_000)
47
+ throw new JcsError("too large");
48
+ const f = stack.pop();
49
+ if (f.kind === "text") {
50
+ parts.push(f.s);
51
+ continue;
52
+ }
53
+ const v = f.v;
54
+ if (v === null)
55
+ parts.push("null");
56
+ else if (typeof v === "boolean")
57
+ parts.push(v ? "true" : "false");
58
+ else if (typeof v === "number")
59
+ parts.push(serializeNumber(v));
60
+ else if (typeof v === "string")
61
+ parts.push(serializeString(v));
62
+ else if (Array.isArray(v)) {
63
+ const frames = [{ kind: "text", s: "[" }];
64
+ v.forEach((x, i) => {
65
+ if (i > 0)
66
+ frames.push({ kind: "text", s: "," });
67
+ frames.push({ kind: "value", v: x });
68
+ });
69
+ frames.push({ kind: "text", s: "]" });
70
+ for (let i = frames.length - 1; i >= 0; i--)
71
+ stack.push(frames[i]);
72
+ }
73
+ else if (typeof v === "object") {
74
+ const o = v;
75
+ const keys = Object.keys(o).filter((k) => o[k] !== undefined).sort(compareKeys);
76
+ const frames = [{ kind: "text", s: "{" }];
77
+ keys.forEach((k, i) => {
78
+ frames.push({ kind: "text", s: (i > 0 ? "," : "") + serializeString(k) + ":" });
79
+ frames.push({ kind: "value", v: o[k] });
80
+ });
81
+ frames.push({ kind: "text", s: "}" });
82
+ for (let i = frames.length - 1; i >= 0; i--)
83
+ stack.push(frames[i]);
84
+ }
85
+ else {
86
+ throw new JcsError("non-JSON value");
87
+ }
88
+ }
89
+ return parts.join("");
90
+ }
91
+ //# sourceMappingURL=jcs.js.map
@@ -0,0 +1,17 @@
1
+ /** Deep-freeze plain data (iterative). */
2
+ export declare function deepFreeze<T>(value: T): T;
3
+ /**
4
+ * Removes trailing characters in `chars`. Linear time: a regex like /[. ]+$/ backtracks
5
+ * quadratically in V8 on a long run that isn't at the end (a 120 KB path took 27 s).
6
+ */
7
+ export declare function trimEndChars(s: string, chars: string): string;
8
+ export declare function isRecord(v: unknown): v is Record<string, unknown>;
9
+ /** Own data property read on a snapshot (null-prototype) object. */
10
+ export declare function get(v: unknown, key: string): unknown;
11
+ export declare function getString(v: unknown, key: string): string | undefined;
12
+ export declare function codePointLength(s: string): number;
13
+ /** RFC 6901 pointer segment escaping. */
14
+ export declare function ptrSeg(k: string | number): string;
15
+ export declare function utf8Length(s: string): number;
16
+ export declare function uniq<T>(xs: Iterable<T>): T[];
17
+ //# sourceMappingURL=misc.d.ts.map
@@ -0,0 +1,77 @@
1
+ // Small shared helpers.
2
+ /** Deep-freeze plain data (iterative). */
3
+ export function deepFreeze(value) {
4
+ const stack = [value];
5
+ const seen = new Set();
6
+ while (stack.length > 0) {
7
+ const v = stack.pop();
8
+ if (v === null || typeof v !== "object" || seen.has(v))
9
+ continue;
10
+ seen.add(v);
11
+ Object.freeze(v);
12
+ for (const k of Object.keys(v))
13
+ stack.push(v[k]);
14
+ }
15
+ return value;
16
+ }
17
+ /**
18
+ * Removes trailing characters in `chars`. Linear time: a regex like /[. ]+$/ backtracks
19
+ * quadratically in V8 on a long run that isn't at the end (a 120 KB path took 27 s).
20
+ */
21
+ export function trimEndChars(s, chars) {
22
+ let e = s.length;
23
+ while (e > 0 && chars.includes(s[e - 1]))
24
+ e--;
25
+ return e === s.length ? s : s.slice(0, e);
26
+ }
27
+ export function isRecord(v) {
28
+ return v !== null && typeof v === "object" && !Array.isArray(v);
29
+ }
30
+ /** Own data property read on a snapshot (null-prototype) object. */
31
+ export function get(v, key) {
32
+ if (!isRecord(v))
33
+ return undefined;
34
+ return Object.prototype.hasOwnProperty.call(v, key) ? v[key] : undefined;
35
+ }
36
+ export function getString(v, key) {
37
+ const x = get(v, key);
38
+ return typeof x === "string" ? x : undefined;
39
+ }
40
+ export function codePointLength(s) {
41
+ let n = 0;
42
+ for (let i = 0; i < s.length; i++) {
43
+ const c = s.charCodeAt(i);
44
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
45
+ const d = s.charCodeAt(i + 1);
46
+ if (d >= 0xdc00 && d <= 0xdfff)
47
+ i++;
48
+ }
49
+ n++;
50
+ }
51
+ return n;
52
+ }
53
+ /** RFC 6901 pointer segment escaping. */
54
+ export function ptrSeg(k) {
55
+ return String(k).replace(/~/g, "~0").replace(/\//g, "~1");
56
+ }
57
+ export function utf8Length(s) {
58
+ let n = 0;
59
+ for (let i = 0; i < s.length; i++) {
60
+ const c = s.charCodeAt(i);
61
+ if (c < 0x80)
62
+ n += 1;
63
+ else if (c < 0x800)
64
+ n += 2;
65
+ else if (c >= 0xd800 && c <= 0xdbff) {
66
+ n += 4;
67
+ i++;
68
+ }
69
+ else
70
+ n += 3;
71
+ }
72
+ return n;
73
+ }
74
+ export function uniq(xs) {
75
+ return [...new Set(xs)];
76
+ }
77
+ //# sourceMappingURL=misc.js.map
@@ -0,0 +1,14 @@
1
+ import { RE2JS } from "re2js";
2
+ type Compiled = ReturnType<typeof RE2JS.compile>;
3
+ export declare function compile(pattern: string, flags?: "i"): Compiled | null;
4
+ export interface ReMatch {
5
+ start: number;
6
+ end: number;
7
+ text: string;
8
+ groups: (string | null)[];
9
+ }
10
+ export declare function findAll(pattern: string, text: string, flags?: "i", max?: number): ReMatch[];
11
+ export declare function test(pattern: string, text: string, flags?: "i"): boolean;
12
+ export declare function isValidPattern(pattern: string): boolean;
13
+ export {};
14
+ //# sourceMappingURL=re.d.ts.map