plainscript-lang 1.0.2 → 1.0.3-beta

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 (67) hide show
  1. package/README.md +194 -736
  2. package/compiler/cli.js +13 -17
  3. package/compiler/generator.js +93 -21
  4. package/compiler/version.js +1 -1
  5. package/docs/CAPABILITY_GAP_AUDIT.md +98 -536
  6. package/docs/PLAINSCRIPT-SPEC.md +308 -557
  7. package/docs/index.html +101 -599
  8. package/docs/website/script.js +59 -1029
  9. package/docs/website/style.css +74 -656
  10. package/examples/ai-providers.pln +7 -0
  11. package/examples/arrays.pln +4 -12
  12. package/examples/async-errors.pln +18 -0
  13. package/examples/auth-api.pln +3 -50
  14. package/examples/auth-sessions.pln +32 -0
  15. package/examples/basics.pln +14 -0
  16. package/examples/bots.pln +13 -0
  17. package/examples/cache-and-jobs.pln +6 -28
  18. package/examples/cache-schedule.pln +22 -0
  19. package/examples/collections.pln +15 -0
  20. package/examples/concurrency.pln +12 -43
  21. package/examples/conditions.pln +22 -0
  22. package/examples/database.pln +6 -39
  23. package/examples/day2.pln +6 -6
  24. package/examples/day3.pln +4 -10
  25. package/examples/deployment.pln +3 -9
  26. package/examples/email-send.pln +3 -22
  27. package/examples/error-handling.pln +6 -54
  28. package/examples/expressions.pln +7 -40
  29. package/examples/file-uploads.pln +5 -34
  30. package/examples/files-and-config.pln +5 -46
  31. package/examples/files.pln +12 -0
  32. package/examples/football-backend/app.pln +21 -20
  33. package/examples/functions.pln +17 -0
  34. package/examples/hello.pln +2 -3
  35. package/examples/http-client.pln +3 -44
  36. package/examples/http.pln +11 -0
  37. package/examples/id-verification/app.pln +4 -3
  38. package/examples/id-verification/make-sample-id.js +29 -42
  39. package/examples/json.pln +11 -0
  40. package/examples/loops.pln +13 -11
  41. package/examples/modules/app.pln +3 -16
  42. package/examples/modules/main.pln +4 -0
  43. package/examples/modules/math.pln +5 -16
  44. package/examples/objects.pln +3 -11
  45. package/examples/ocr.pln +22 -0
  46. package/examples/packages.pln +6 -0
  47. package/examples/record-kinds.pln +6 -42
  48. package/examples/records.pln +15 -0
  49. package/examples/rest-api-fetch.pln +6 -90
  50. package/examples/rest-api.pln +5 -65
  51. package/examples/scheduled-tasks.pln +4 -23
  52. package/examples/search-and-filter.pln +4 -34
  53. package/examples/server.pln +5 -24
  54. package/examples/sessions-and-cookies.pln +4 -50
  55. package/examples/sqlite.pln +23 -0
  56. package/examples/start.pln +2 -2
  57. package/examples/stdlib.pln +4 -41
  58. package/examples/telegram-ai-bot.pln +19 -0
  59. package/examples/telegram-bot.pln +4 -40
  60. package/examples/testing.pln +13 -0
  61. package/examples/web-api.pln +27 -0
  62. package/examples/web-app.pln +4 -16
  63. package/examples/websocket-server.pln +5 -26
  64. package/examples/websocket.pln +13 -0
  65. package/examples/whatsapp-bot/pairing.pln +4 -5
  66. package/examples/whatsapp-bot/qr.pln +7 -3
  67. package/package.json +2 -2
package/compiler/cli.js CHANGED
@@ -88,13 +88,13 @@ ${section('THE LANGUAGE IN EIGHT LINES')}
88
88
  try ... recover as err ... done retry 3 times every 5s errors
89
89
 
90
90
  ${section('ALSO SHIPPED')}
91
- Comparisons and stdlib (v1.0) · PlainScript Expressions (v1.1) ·
92
- JavaScript gateway with ask (v1.1.1) · OCR · Telegram bots ·
93
- WhatsApp bots (v2.1.1) ·
94
- email · schedules · WebSocket · cache (v2.1) ·
95
- sessions · uploads · cookies · rate limits · api keys · OAuth (v2.1.1)
91
+ Comparisons and stdlib · PlainScript Expressions ·
92
+ console input with ask · OCR · Telegram bots ·
93
+ WhatsApp bots ·
94
+ email · schedules · WebSocket · cache ·
95
+ sessions · uploads · cookies · rate limits · api keys · OAuth
96
96
  JSON body · redirect · AI chat/embeddings · vector similarity ·
97
- paginate · collection & string primitives (v2.2)
97
+ paginate · collection & string primitives
98
98
 
99
99
  ${section('FIRST RUN')}
100
100
  plainscript new hello scaffolds hello/ with a live web app
@@ -525,34 +525,30 @@ function cmdNew(projectName) {
525
525
  fs.mkdirSync(path.join(dir, 'public'));
526
526
  fs.mkdirSync(path.join(dir, 'src'));
527
527
 
528
- // src/app.pln — starter Express app
529
- fs.writeFileSync(path.join(dir, 'src', 'app.pln'), `use express
530
-
531
- remember app as express()
528
+ // src/app.pln — starter web app
529
+ fs.writeFileSync(path.join(dir, 'src', 'app.pln'), `web app
532
530
 
533
531
  serve folder "public"
534
532
 
535
- when someone visits "/"
533
+ route get "/"
536
534
  reply "Hello from PlainScript!"
537
535
  done
538
536
 
539
- when someone visits "/api/status"
537
+ route get "/api/status"
540
538
  reply json
541
539
  status is "ok"
542
- version is "1.0"
540
+ version is "1.0.3-beta"
543
541
  done
544
542
  done
545
543
 
546
- listen on 3000
547
- show "Server running at http://localhost:3000"
548
- done
544
+ start 3000
549
545
  `);
550
546
 
551
547
  // package.json — plain Node semantics; PlainScript itself is a devDependency and
552
548
  // deployment only needs the generated dist/ output.
553
549
  fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
554
550
  name,
555
- version: '1.0.1',
551
+ version: VERSION,
556
552
  description: `A PlainScript v${VERSION} application`,
557
553
  main: 'dist/app.js',
558
554
  scripts: {
@@ -575,21 +575,32 @@ const BUILTIN_DECLARATIONS = {
575
575
  ` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
576
576
  `}`,
577
577
  ].join('\n'),
578
- // v2.2.0 — AI/ML runtime. `chat` and `embeddings` talk to any OpenAI-compatible
579
- // completions/embeddings endpoint (API key and base URL from options or env),
580
- // while `similarity` is pure vector math and runs fully offline.
578
+ // 1.0.3-beta — provider-neutral AI runtime. `chat` and `embedText` speak
579
+ // OpenAI-compatible APIs, including Groq, OpenRouter, Together, Fireworks,
580
+ // and DeepSeek. A custom `base` and `key` can be supplied per call.
581
581
  ai: [
582
- `function __aiTags() {`,
583
- ` return { key: process.env.OPENAI_API_KEY, base: (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\\/$/, '') };`,
582
+ `function __aiTags(options = {}) {`,
583
+ ` const provider = String(options.provider || process.env.PLAINSCRIPT_AI_PROVIDER || 'openai').toLowerCase();`,
584
+ ` const providers = {`,
585
+ ` openai: { key: process.env.OPENAI_API_KEY, base: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1' },`,
586
+ ` groq: { key: process.env.GROQ_API_KEY, base: process.env.GROQ_BASE_URL || 'https://api.groq.com/openai/v1' },`,
587
+ ` openrouter: { key: process.env.OPENROUTER_API_KEY, base: process.env.OPENROUTER_BASE_URL || 'https://openrouter.ai/api/v1' },`,
588
+ ` together: { key: process.env.TOGETHER_API_KEY, base: process.env.TOGETHER_BASE_URL || 'https://api.together.xyz/v1' },`,
589
+ ` fireworks: { key: process.env.FIREWORKS_API_KEY, base: process.env.FIREWORKS_BASE_URL || 'https://api.fireworks.ai/inference/v1' },`,
590
+ ` deepseek: { key: process.env.DEEPSEEK_API_KEY, base: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/v1' },`,
591
+ ` };`,
592
+ ` const selected = providers[provider] || { key: process.env[provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY'], base: process.env[provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_BASE_URL'] };`,
593
+ ` return { provider, key: options.key || selected.key, base: (options.base || selected.base || '').replace(/\\/$/, '') };`,
584
594
  `}`,
585
- `async function __aiPost(tags, path, body) {`,
595
+ `async function __aiPost(tags, path, body, options = {}) {`,
586
596
  ` if (typeof fetch !== 'function') {`,
587
597
  ` throw new Error('AI calls need Node.js 18 or newer (global fetch is missing): ' + process.version);`,
588
598
  ` }`,
589
- ` if (!tags.key) throw new Error('No API key for AI. Set env OPENAI_API_KEY.');`,
599
+ ` if (!tags.key) throw new Error('No API key for AI provider ' + tags.provider + '. Set ' + tags.provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY or pass key in chat options.');`,
600
+ ` const headers = Object.assign({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key }, options.headers || {});`,
590
601
  ` const response = await fetch(tags.base + path, {`,
591
602
  ` method: 'POST',`,
592
- ` headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key },`,
603
+ ` headers,`,
593
604
  ` body: JSON.stringify(body),`,
594
605
  ` });`,
595
606
  ` const text = await response.text();`,
@@ -599,19 +610,21 @@ const BUILTIN_DECLARATIONS = {
599
610
  ` return data;`,
600
611
  `}`,
601
612
  `async function __aiChat(model, messages, options) {`,
602
- ` const tags = __aiTags();`,
603
- ` if (options && options.key) tags.key = options.key;`,
604
- ` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
613
+ ` options = options || {};`,
614
+ ` const tags = __aiTags(options);`,
605
615
  ` if (typeof messages === 'string') messages = [{ role: 'user', content: messages }];`,
606
- ` const data = await __aiPost(tags, '/chat/completions', { model: model, messages: messages });`,
616
+ ` const body = { model: model, messages: messages };`,
617
+ ` if (options.temperature != null) body.temperature = options.temperature;`,
618
+ ` if (options.maxTokens != null) body.max_tokens = options.maxTokens;`,
619
+ ` if (options.responseFormat != null) body.response_format = options.responseFormat;`,
620
+ ` const data = await __aiPost(tags, '/chat/completions', body, options);`,
607
621
  ` const choice = data.choices && data.choices[0];`,
608
622
  ` return choice && choice.message ? choice.message.content : '';`,
609
623
  `}`,
610
624
  `async function __aiEmbed(model, text, options) {`,
611
- ` const tags = __aiTags();`,
612
- ` if (options && options.key) tags.key = options.key;`,
613
- ` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
614
- ` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) });`,
625
+ ` options = options || {};`,
626
+ ` const tags = __aiTags(options);`,
627
+ ` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) }, options);`,
615
628
  ` return (data.data && data.data[0] && data.data[0].embedding) || [];`,
616
629
  `}`,
617
630
  `function __aiSimilarity(a, b) {`,
@@ -1013,15 +1026,16 @@ const BUILTIN_DECLARATIONS = {
1013
1026
  ` if (!resolved) throw new Error('Telegram: bot token is missing. Use: bot "YOUR_BOT_TOKEN"');`,
1014
1027
  ` token = resolved; // bind the API transport to this bot's credential`,
1015
1028
  ` let offset = 0;`,
1016
- ` const onText = async (chatId, text) => {`,
1029
+ ` const onText = async (chatId, text, rawMessage = {}) => {`,
1030
+ ` const baseContext = { chatId, chat: rawMessage.chat || { id: chatId }, message: rawMessage, text, args: text.split(' ').slice(1), matches: [] };`,
1017
1031
  ` for (const { matcher, handler } of handlers.pattern) {`,
1018
1032
  ` const match = text.match(matcher);`,
1019
- ` if (match) { await handler({ chatId, text, matches: match }); return; }`,
1033
+ ` if (match) { await handler({ ...baseContext, matches: match }); return; }`,
1020
1034
  ` }`,
1021
1035
  ` const first = text.split(' ')[0];`,
1022
1036
  ` for (const { matcher, handler } of handlers.command) {`,
1023
1037
  ` if (first === matcher) {`,
1024
- ` await handler({ chatId, text, args: text.split(' ').slice(1) });`,
1038
+ ` await handler(baseContext);`,
1025
1039
  ` return;`,
1026
1040
  ` }`,
1027
1041
  ` }`,
@@ -1029,7 +1043,7 @@ const BUILTIN_DECLARATIONS = {
1029
1043
  ` const onCallback = async (data, message) => {`,
1030
1044
  ` for (const { matcher, handler } of handlers.callback) {`,
1031
1045
  ` if (data === matcher) {`,
1032
- ` await handler({ data, message, chatId: message.chat.id });`,
1046
+ ` await handler({ data, message, chatId: message.chat.id, chat: message.chat, text: message.text || '', args: [], matches: [] });`,
1033
1047
  ` return;`,
1034
1048
  ` }`,
1035
1049
  ` }`,
@@ -1049,7 +1063,7 @@ const BUILTIN_DECLARATIONS = {
1049
1063
  ` const chat = (update.message || (update.callback_query || {}).message || {}).chat;`,
1050
1064
  ` if (chat) chats.set(chat.id, chat);`,
1051
1065
  ` if (update.message && update.message.text != null) {`,
1052
- ` await onText(update.message.chat.id, update.message.text);`,
1066
+ ` await onText(update.message.chat.id, update.message.text, update.message);`,
1053
1067
  ` } else if (update.callback_query && update.callback_query.data != null) {`,
1054
1068
  ` await onCallback(update.callback_query.data, update.callback_query.message);`,
1055
1069
  ` }`,
@@ -1161,6 +1175,22 @@ const BUILTIN_DECLARATIONS = {
1161
1175
  ensureBuiltin(context, 'telegram');
1162
1176
  return `Telegram.editMessage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1163
1177
  },
1178
+ telegramCall: (args, context) => {
1179
+ ensureBuiltin(context, 'telegram');
1180
+ requireArgs('telegramCall', args, 1, 'telegramCall("getMe", {})');
1181
+ markAsync(context);
1182
+ const method = generateExpr(args[0], context);
1183
+ const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
1184
+ return `await Telegram.call(${method}, ${params})`;
1185
+ },
1186
+ telegramApi: (args, context) => {
1187
+ ensureBuiltin(context, 'telegram');
1188
+ requireArgs('telegramApi', args, 1, 'telegramApi("getMe", {})');
1189
+ markAsync(context);
1190
+ const method = generateExpr(args[0], context);
1191
+ const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
1192
+ return `await Telegram.call(${method}, ${params})`;
1193
+ },
1164
1194
  // v2.1.0 — HTTP request accessors. Only meaningful inside a route handler,
1165
1195
  // where Express provides req/res.
1166
1196
  param: (args, context) => routeAccessor('param', 'params', args, context),
@@ -1600,20 +1630,42 @@ const BUILTIN_DECLARATIONS = {
1600
1630
  // offline cosine similarity over any two equal-length numeric vectors.
1601
1631
  chat: (args, context) => {
1602
1632
  ensureBuiltin(context, 'ai');
1633
+ requireArgs('chat', args, 2, 'chat("model", "message")');
1603
1634
  markAsync(context);
1604
1635
  const model = generateExpr(args[0], context);
1605
1636
  const messages = generateExpr(args[1], context);
1606
1637
  const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
1607
1638
  return `await __aiChat(${model}, ${messages}, ${options})`;
1608
1639
  },
1640
+ chatWith: (args, context) => {
1641
+ ensureBuiltin(context, 'ai');
1642
+ requireArgs('chatWith', args, 3, 'chatWith("groq", "model", "message")');
1643
+ markAsync(context);
1644
+ const provider = generateExpr(args[0], context);
1645
+ const model = generateExpr(args[1], context);
1646
+ const messages = generateExpr(args[2], context);
1647
+ const options = args.length > 3 && args[3] != null ? generateExpr(args[3], context) : '{}';
1648
+ return `await __aiChat(${model}, ${messages}, Object.assign({}, ${options}, { provider: ${provider} }))`;
1649
+ },
1609
1650
  embedText: (args, context) => {
1610
1651
  ensureBuiltin(context, 'ai');
1652
+ requireArgs('embedText', args, 2, 'embedText("model", "text")');
1611
1653
  markAsync(context);
1612
1654
  const model = generateExpr(args[0], context);
1613
1655
  const text = generateExpr(args[1], context);
1614
1656
  const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
1615
1657
  return `await __aiEmbed(${model}, ${text}, ${options})`;
1616
1658
  },
1659
+ embedWith: (args, context) => {
1660
+ ensureBuiltin(context, 'ai');
1661
+ requireArgs('embedWith', args, 3, 'embedWith("groq", "model", "text")');
1662
+ markAsync(context);
1663
+ const provider = generateExpr(args[0], context);
1664
+ const model = generateExpr(args[1], context);
1665
+ const text = generateExpr(args[2], context);
1666
+ const options = args.length > 3 && args[3] != null ? generateExpr(args[3], context) : '{}';
1667
+ return `await __aiEmbed(${model}, ${text}, Object.assign({}, ${options}, { provider: ${provider} }))`;
1668
+ },
1617
1669
  similarity: (args, context) => {
1618
1670
  ensureBuiltin(context, 'ai');
1619
1671
  return `__aiSimilarity(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
@@ -2122,6 +2174,14 @@ function requireOneArg(name, args) {
2122
2174
  }
2123
2175
  }
2124
2176
 
2177
+ function requireArgs(name, args, minimum, example) {
2178
+ if (args.length < minimum) {
2179
+ throw new Error(
2180
+ `"${name}" needs at least ${minimum} argument${minimum === 1 ? '' : 's'}.\n\nExample:\n ${example}`
2181
+ );
2182
+ }
2183
+ }
2184
+
2125
2185
  // Set to true while generating inside a route handler body.
2126
2186
  // Remaps PlainScript's "request" → "req" and "response" → "res".
2127
2187
  let _inRoute = false;
@@ -3358,6 +3418,18 @@ function generateExpr(node, context = createGenerationContext()) {
3358
3418
  // Inside route handlers, remap PlainScript's request/response to req/res
3359
3419
  if (_inRoute && node.name === 'request') return 'req';
3360
3420
  if (_inRoute && node.name === 'response') return 'res';
3421
+ if (_inTelegram) {
3422
+ const telegramContext = {
3423
+ message: 'ctx.message',
3424
+ chat: 'ctx.chat',
3425
+ chatId: 'ctx.chatId',
3426
+ text: 'ctx.text',
3427
+ args: 'ctx.args',
3428
+ matches: 'ctx.matches',
3429
+ data: 'ctx.data',
3430
+ };
3431
+ if (telegramContext[node.name]) return telegramContext[node.name];
3432
+ }
3361
3433
  // Inside WhatsApp "on message" handlers, PlainScript's "message" is the
3362
3434
  // normalized record of the current delivery.
3363
3435
  if (_inWhatsApp && node.name === 'message') return '__waCtx.message';
@@ -1,6 +1,6 @@
1
1
  // Single source of truth for the compiler version.
2
2
  // Consumed by cli.js help/version output.
3
3
 
4
- const VERSION = '1.0.2';
4
+ const VERSION = '1.0.3-beta';
5
5
 
6
6
  module.exports = { VERSION };